FrontEnd/React

timeago.js로 시간 포맷팅하기 - "방금 전", "3시간 전"

Damdadira 2025. 7. 2. 10:35

개인 프로젝트를 진행하다 시간을 가져오는 부분이 있었는데 "2025-05-06T13:29:04Z" 이런 형태로 출력되고 있었다.

실제로 화면에 보여줄 때는 이런 형식으로 보여주면 안 될 거 같아서 timeago 라이브러리를 사용해 변환을 시켜줬다.

 

 

 

timeago.js란?

JavaScript에서 "방금 전", "5시간 전", "2일 전" 등의 상대적인 시간 포맷을 쉽게 만들어주는 라이브러리다.

 

 

 

설치 방법
#터미널에 명령어 입력
npm install timeago.js

 

 

 

기본 사용법
import { format } from 'timeago.js';

format(new Date());     // '방금 전'

 

 

 

한국어 포맷 사용

index.js

import { format, register } from "timeago.js";
import koLocale from "timeago.js/lib/lang/ko";

register('ko', koLocale);

export function formatAgo(data, lang = 'en') {
  return format(data, lang);
}

 

Videos.jsx

export default function Videos ({publishedAt}) {
  return <span>{formatAgo(publishedAt, 'ko')}</span>
}

 

실행 화면

실행 화면(Videos)

 

 

 

React 컴포넌트를 쓰고 싶다면 react-timeago, 함수 기반 유틸로 사용하고 싶다면 timeago.js가 적합하다.

시간 포맷이 필요한 곳에 반복적으로 쓰기 위해 공통 함수로 추출해서 만들어두었다.

 

 

 

공식 문서 참고

npm

 

timeago.js

timeago.js is a simple library (only 1kb) to used to format datetime with `*** time ago` statement. eg: '3 hours ago'. localization supported.. Latest version: 4.0.2, last published: 6 years ago. Start using timeago.js in your project by running `npm i tim

www.npmjs.com

 

github

 

timeago.js/README.md at master · hustcc/timeago.js

:clock8: :hourglass: timeago.js is a tiny(2.0 kb) library used to format date with `*** time ago` statement. - hustcc/timeago.js

github.com