[JS] Date 라이브러리 Day.js
1. Day.js
1.1 개요
JavaScript 날짜 관련 라이브러리중 가장 가벼운 라이브러리로, 더 이상 업데이트가 되지 않는 Moment.js의 대안으로 많이 사용된다.
1.2 사용 예시
설치
yarn add dayjs
기본 사용법
import dayjs from "dayjs";
const date = dayjs("2024-08-19 14:45:30");
console.log(date.year()); // 2024 (연도)
console.log(date.month() + 1); // 8 (월, 0부터 시작하므로 +1)
console.log(date.date()); // 19 (일)
console.log(date.hour()); // 14 (시)
console.log(date.minute()); // 45 (분)
console.log(date.second()); // 30 (초)
console.log(date.format("YYYY-MM-DD HH:mm:ss")); // '2024-08-19 14:45:30'
날짜 포맷팅
import dayjs from "dayjs";
const date = dayjs("2024-08-19 14:45:30");
console.log(date.format()); // 2024-08-19T14:45:30+09:00
console.log(date.format("YYYY년 MM월 DD일")); // 2024년 08월 19일
console.log(date.format("YYYY년 M월 D일 HH시 mm분")); // 2024년 8월 19일 14시 45분
console.log(date.format("YYYY/MM/DD HH:mm:ss")); // 2024/08/19 14:45:30
날짜 정보 얻기
import dayjs from "dayjs";
const now = dayjs();
console.log(now.get("year")); // 2024 (년)
console.log(now.get("y")); // 2024 (년)
console.log(now.get("month")); // 7 (월 - 0~11, 실제로는 8월)
console.log(now.get("M")); // 7 (월 - 0~11, 실제로는 8월)
console.log(now.get("date")); // 19 (일)
console.log(now.get("D")); // 19 (일)
console.log(now.get("day")); // 월요일 (요일 - 일요일 : 0, 토요일 : 6)
console.log(now.get("d")); // 월요일 (요일 - 일요일 : 0, 토요일 : 6)
console.log(now.get("hour")); // 14 (시)
console.log(now.get("h")); // 14 (시)
console.log(now.get("minute")); // 45 (분)
console.log(now.get("m")); // 45 (분)
console.log(now.get("second")); // 30 (초)
console.log(now.get("s")); // 30 (초)
console.log(now.get("millisecond")); // 500 (밀리초, 예시)
console.log(now.get("ms")); // 500 (밀리초, 예시)
ㅋ;
날짜 추가 및 빼기
import dayjs from "dayjs";
const date = dayjs("2023-02-24 10:30:21");
console.log(date.add(1, "year").format()); // 2024년
console.log(date.add(1, "month").format()); // 3월 24일
console.log(date.add(1, "week").format()); // 3월 3일
console.log(date.subtract(1, "year").format()); // 2022년
console.log(date.subtract(1, "month").format()); // 1월 24일
console.log(date.subtract(1, "week").format()); // 2월 17일
댓글남기기