react-native 온라인 강의를 듣다가 나중을 위해 기록합니다.
(참고한 강좌 : 패스트캠퍼스의 React Native 를 활용한 빠르고 완성도 높은 앱 개발 초격차 패키지 Online)
1. Dayjs 소개
javascript에서 기본으로 제공하는 date 함수를 사용하기 보다는 외부라이브러리를 사용하는 걸 추천한다.
대표적으로 Momentjs 와 Dayjs가 있는 데, Momentjs는 이제 더이상 업데이트가 잘 이루어지지 않는다.
그래서 2024년 11월 기준으로 Dayjs사용을 권장한다.
https://www.jsdelivr.com/package/npm/dayjs
jsDelivr - A free, fast, and reliable CDN for JS and Open Source
Optimized for JS and ESM delivery from npm and GitHub. Works with all web formats. Serving more than 150 billion requests per month.
www.jsdelivr.com
npm install dayjs --save
Dayjs 사용 방법
0. Dayjs 라이브러리 호출하기(import)
import dayjs from "dayjs";
// 아래와 같이 특정 내부 함수를 사용하려면 따로 불러오는 게 좋다.
// 그래야만, 에디터에서 자동 완성 기능이 활성화 된다.
import isBetween from "dayjs/plugin/isBetween";
import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter";
dayjs.extend(isBetween);
dayjs.extend(isSameOrBefore);
dayjs.extend(isSameOrAfter);
1. 특정 날짜 또는 현재 날짜 생성
const now = dayjs("2022-11-04 16:01:30");
// const now = dayjs();
2. 시간 지정 - set
console.log(
"1. set minute - hh",
dayjs(now).set("minute", 5).format("YYYY.MM.DD hh:mm:ss a A")
);
console.log(
"2. set minute - HH",
dayjs(now).set("minute", 5).format("YYYY.MM.DD HH:mm:ss")
);
console.log(
"3. set hour",
dayjs(now).set("hour", 10).format("YYYY.MM.DD HH:mm:ss")
);
3. 시간 가져오기 - get
console.log("4. get year", dayjs(now).get("year"));
console.log("5. get month", dayjs(now).get("month")); // 0~11(1월~12월)
console.log("6. get date", dayjs(now).get("date"));
console.log("7. get day", dayjs(now).get("day")); // 0:일 ~ 6:토
console.log("8. get second", dayjs(now).get("second"));
4. 시간 끼리의 계산
console.log(
"9. add hour",
dayjs(now).add(3, "hour").format("YYYY.MM.DD HH:mm:ss")
);
console.log(
"10. subtract hour",
dayjs(now).subtract(3, "hour").format("YYYY.MM.DD HH:mm:ss")
);
5. 시간 쿼리 또는 비교
console.log("11. startOf", dayjs(now).startOf("month").format("YYYY.MM.DD"));
console.log("12. endOf", dayjs(now).endOf("month").format("YYYY.MM.DD"));
const aDate = dayjs("2022-10-29 15:00:20");
const bDate = dayjs("2022-10-29 16:00:00");
console.log("13. isSame month", dayjs(aDate).isSame(bDate, "month"));
console.log("14. isSame hour", dayjs(aDate).isSame(bDate, "hour"));
console.log("15. isBefore", dayjs(aDate).isBefore(bDate));
console.log("16. isBefore date", dayjs(aDate).isBefore(bDate, "date"));
console.log("17. isAfter a,b", dayjs(aDate).isAfter(bDate));
console.log("18. isAfter b,a", dayjs(bDate).isAfter(aDate));
console.log("19. isSameOrBefore", dayjs(aDate).isSameOrBefore(bDate, "date"));
console.log("20. isSameOrAfter", dayjs(aDate).isSameOrAfter(bDate, "date"));
console.log(
"21. isBetween",
dayjs("2022-10-29 15:30:00").isBetween(aDate, bDate)
);
console.log(
"22. isBetween date",
dayjs("2022-10-29 15:30:00").isBetween(aDate, bDate, "date")
);
console.log("23. diff minute a,b", dayjs(aDate).diff(bDate, "minute"));
console.log("24. diff minute b,a", dayjs(bDate).diff(aDate, "minute"));
최근댓글