본문 바로가기
📍 Front-End/🜸 JavaScript

day.js (Javascript 날짜 라이브러리) 사용법

by 예리Yelee 2023. 5. 16.
반응형

날짜 라이브러리로 많이 쓰이는 moment.js 보다
약 33배나 가벼운 day.js 라이브러리 사용법에 대해 포스팅해보겠습니다

 

✔️  설치

 

dayjs

2KB immutable date time library alternative to Moment.js with the same modern API . Latest version: 1.11.7, last published: 5 months ago. Start using dayjs in your project by running `npm i dayjs`. There are 11592 other projects in the npm registry using d

www.npmjs.com

 

npm i dayjs --save // npm 사용할때
yarn add dayjs // yarn 사용할때

 

 

✔️ 사용법

1.  현재 날짜 구하기

아래와 같이 format을 이용하여 원하는 포맷으로 날짜를 출력할 수 있다

import dayjs from 'dayjs';

dayjs().get('year')
dayjs().get('month') // 0에서부터 시작하여 1월은 0이다
dayjs().get('date')
dayjs().get('day') // 0-6까지 있고 0은 일요일이다
dayjs().get('hour')
dayjs().get('minute')
dayjs().get('second')
dayjs().get('millisecond')

 

2. 원하는 포맷으로 출력하기

import dayjs from 'dayjs';

console.log(dayjs().format('YYYY MM DD HH:mm:ss'));
// 2023 05 16 14:00:00

 

 

YY 18 Two-digit year
YYYY 2018 Four-digit year
M 1-12 The month, beginning at 1
MM 01-12 The month, 2-digits
MMM Jan-Dec The abbreviated month name
MMMM January-December The full month name
D 1-31 The day of the month
DD 01-31 The day of the month, 2-digits
d 0-6 The day of the week, with Sunday as 0
dd Su-Sa The min name of the day of the week
ddd Sun-Sat The short name of the day of the week
dddd Sunday-Saturday The name of the day of the week
H 0-23 The hour
HH 00-23 The hour, 2-digits
h 1-12 The hour, 12-hour clock
hh 01-12 The hour, 12-hour clock, 2-digits
m 0-59 The minute
mm 00-59 The minute, 2-digits
s 0-59 The second
ss 00-59 The second, 2-digits
SSS 000-999 The millisecond, 3-digits
Z +05:00 The offset from UTC, ±HH:mm
ZZ +0500 The offset from UTC, ±HHmm
A AM PM  
a am pm

 

2. 날짜를 dayjs 객체로 변경하기

console.log(dayjs('2023-05-15')) // return new Object

 

3.  시간 조작하기

dayjs().add(7, 'day') // 7일후
dayjs().add(1, 'week') // 1주일후

dayjs().subtract(7, 'year') // 7년 전

dayjs().startOf('year') // 현재 년도의 첫번째 날 00시 00분 00초
dayjs().endOf('month') // 현재 달의 마지막 날짜 23시 59분 59초

 

두 번째 인자로 day, week, month, year, hour, minute, second, millisecond를 넣을 수 있다

 


✨ 그 외 사용법은 day.js. github에 친절하게 설명되어 있으니 참고하세요✨

 

GitHub - iamkun/dayjs: ⏰ Day.js 2kB immutable date-time library alternative to Moment.js with the same modern API

⏰ Day.js 2kB immutable date-time library alternative to Moment.js with the same modern API - GitHub - iamkun/dayjs: ⏰ Day.js 2kB immutable date-time library alternative to Moment.js with the same m...

github.com

 

반응형

댓글