🍞 Front-End/React

[React] 시간 처리하기 (몇 분 전, 몇 시간 전)

박빵이 2022. 11. 26. 16:25

프론트에서 사용자와 마주하는 디테일한 부분을 신경 쓰는 것은 매우 중요하다. 그래서 업로드 시간을 그대로 노출시키는 게 아니라 보여주기 전에 한 번 더 가공을 해서 보여주는 것을 구현할 것이다.

 

그렇기 때문에 오늘은 react-moment라는 라이브러리를 사용해볼 것이다!

이 라이브러리를 사용하면 손쉽게 구현 가능하다.

 

✅ react-moment

- react-moment는 react에서 moment를 편리하게 사용할 수 있게 만들어 놓은 라이브러리다.

- 심지어 react-moment는 별다른 작업을 하지 않아도 실시간으로 시간이 변하게 제공을 해준다.

 

GitHub - headzoo/react-moment: React component for the moment date library.

React component for the moment date library. Contribute to headzoo/react-moment development by creating an account on GitHub.

github.com

 

설치

react-moment는 moment가 dependency 되어 있기 때문에 moment부터 설치해주어야 한다.

npm i moment react-moment

 

코드

  // 업로드 시간 가공
  const displayCreateAt = (createdAt) => {
    const date = new Date(createdAt);
    const now = Date.now();
    const milliSeconds = now - date;

    const seconds = milliSeconds / 1000;
    const minutes = seconds / 60;
    const hours = minutes / 60;
    const days = hours / 24;
    const months = days / 30;
    const years = months / 12;

    if (seconds < 60) {
      return "방금 전";
    } else if (minutes < 60) {
      return `${Math.floor(minutes)}분 전`;
    } else if (hours < 24) {
      return `${Math.floor(hours)}시간 전`;
    } else if (days < 30) {
      return `${Math.floor(days)}일 전`;
    } else if (months < 12) {
      return `${Math.floor(months)}달 전`;
    } else {
      return `${Math.floor(years)}년 전`;
    }
  };

 

[React] 리액트에서 react-moment, moment.js 사용하여 실시간으로 변경되는 시간 만들기

✔ moment.js Moment js는 시간이 포함된 데이터를 받아 조작해야 할 경우 가장 많이 사용되는 편리한 라이브러리입니다. 스터디를 모집하는 사이드 프로젝트를 만들 때 사용하였습니다. 현재 시간에

haranglog.tistory.com