본문 바로가기
React

[React] date-fns 를 이용하여 날짜 형식 변경하기 - 떽떽대는 개발공부

by 떽이 2021. 4. 21.

 

 

 

 

 

 

 

오늘은 date-fns 라이브러리를 이용하여 날짜 형식을 변경을 해보자.

먼저 필요한 라이브러리 설치를 한다.

// 버전에 따라 string 사용이 안되는 경우도 있으니 버전 확인 후 install
npm i date-fns@1.30.1
npm i -D babel-plugin-date-fns@0.2.1

 

craco 에서 date-fns 를 설정 해준다.

craco.config.js

module.exports = function() {
return {
babel: {
plugins: ['date-fns'],
}
}
}

 

dateUtils 라는 파일을 하나 생성하고 작성한다.

src/utils/dateUtils.ts

import { format } from 'date-fns'
export const getFormattedDate = (
date: Date | string | number = new Date(),
givenFormat: string = 'YYYY.MM.DD',
options: {
locale?: Object
} = { locale: enLocale },
) => {
return format(date, givenFormat, options)
}

 

형식 변경이 필요한 부분에서 사용하면 간단하게 완료 된다.

src/components/Temp.tsx

import React from 'react'
import { getFormattedDate } from '@/utils/dateUtils'
export const Temp = () => {
const date: string = new Date().toString()
const result: string = getFormattedDate(date, 'DD MMM YYYY')
return (
<div>
변경 전 : {date}
</div>
<div>
변경 후 : {result}
</div>
)
}

 

결과는 아래와 같다.

  • Year
y 0, 1, 2, 3, 4, 5, ...
yo 0th, 1st, 2nd, 3rd, 4th, 5th, ...
yy 00, 01, 02, ..., 10, 11, ...
yyy 000, 001, 002, ..., 010, 011, ..., 2021, ...
yyyy 0000, 0001, 0002, ..., 0010, 0011, ...2021, ...

 

  • Month
M 1, 2, 3, 4, 5, ..., 12
Mo 1st, 2nd, 3rd, ..., 12th
MM 01, 02, 03, 04, ..., 12
MMM Jan, Feb, Mar, Apr, ..,. Dec
MMMM January, February, March, April, ..., December
MMMMM J, F, M, A, ..., D

 

  • Day of month
d 1, 2, 3, 4, 5, ..., 31
do 1st, 2nd, 4rd, 4th, 5th, ..., 31st
dd 01, 02, 03, 04, 05, ..., 31

 

  • Day of year
D 1, 2, 3, 4, ..., 365
Do 1st, 2nd, 3rd, 4th, ..., 365th
DD 01, 02, 03, 04, ..., 365
DDD 001, 002, 003, 004, ..., 365

 

  • Day of week
E~EEE Sun, Mon, Tue, Sun, Mon, Tue, Wed, Thu, Fri, Sat
EEEE Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,  Saturday
EEEEE S, M, T, W, T, F, S
EEEEEE Su, Mo, Tu, We, Th, Fr, Sa

 

  • Hour (24h)
H 0, 1, 2, 3, 4, ..., 23
Ho 0th, 1st, 2nd, 3rd, 4th, ..., 23rd
HH 00, 01, 02, 03, 04, ..., 23

 

  • Hour (12h)
h 1, 2, 3, 4, ..., 12
ho 1st, 2nd, 3rd, 4th, ..., 12th
hh 01, 02, 03, 04, ..., 12

 

  • Minute
m 0, 1, 2, 3, 4, ..., 59
mo 0th, 1st, 2nd, 3rd, 4th, ..., 59th
mm 00, 01, 02, 03, 04, ..., 59

 

  • Second
s 0, 1, 2, 3, 4, ..., 59
so 0th, 1st, 2nd, 3rd, 4th, ..., 59th
ss 00, 01, 02, 03, 04, ..., 59

 

 

 

 

 

댓글