moment.js (날짜, 시간 계산)

부가 설명
Tags
date
 

설치

$ yarn add moment

시간 덧셈 방법

/*------ 시간 계산하기 기본 ------*/ const tmpTime = moment({hour:6, minute:15}).add(60, 'm'); console.log("60분 후 :", tmpTime.hours(), tmpTime.minutes()); //설정시간 6:15으로 설정하고, 60분 더한 결과를 tmpTime에 담음. //계산결과 7:15으로 맞음~! /*------ 널패딩 추가하여 hh:mm 형태로 출력하기 ------*/ //널패딩 추가 함수 function fillZero(width, str){ return str.length >= width ? str:new Array(width-str.length+1).join('0')+str;//남는 길이만큼 0으로 채움 } const tmpTime = moment({hour:6, minute:0}).add(30, 'm'); const tmpHour = tmpTime.hours().toString(); const tmpMinutes = tmpTime.minutes().toString(); console.log("30분 후 :",tmpTime, tmpHour, tmpMinutes); //출력 결과 06:30 /*-------------------------------------------*/
 

Key Shorthand

years y quarters Q months M weeks w days d hours h minutes m seconds s milliseconds ms

Format Dates

moment().format('MMMM Do YYYY, h:mm:ss a'); // February 10th 2021, 2:32:56 am moment().format('dddd'); // Wednesday moment().format("MMM Do YY"); // Feb 10th 21 moment().format('YYYY [escaped] YYYY'); // 2021 escaped 2021 moment().format(); // 2021-02-10T02:32:56+09:00

Relative Time

moment("20111031", "YYYYMMDD").fromNow(); // 9 years ago moment("20120620", "YYYYMMDD").fromNow(); // 9 years ago moment().startOf('day').fromNow(); // 3 hours ago moment().endOf('day').fromNow(); // in 21 hours moment().startOf('hour').fromNow(); // 33 minutes ago

Calendar Time

moment().subtract(10, 'days').calendar(); // 01/31/2021 moment().subtract(6, 'days').calendar(); // Last Thursday at 2:32 AM moment().subtract(3, 'days').calendar(); // Last Sunday at 2:32 AM moment().subtract(1, 'days').calendar(); // Yesterday at 2:32 AM moment().calendar(); // Today at 2:32 AM moment().add(1, 'days').calendar(); // Tomorrow at 2:32 AM moment().add(3, 'days').calendar(); // Saturday at 2:32 AM moment().add(10, 'days').calendar(); // 02/20/2021

Multiple Locale Support

moment.locale(); // en moment().format('LT'); // 2:32 AM moment().format('LTS'); // 2:32:56 AM moment().format('L'); // 02/10/2021 moment().format('l'); // 2/10/2021 moment().format('LL'); // February 10, 2021 moment().format('ll'); // Feb 10, 2021 moment().format('LLL'); // February 10, 2021 2:32 AM moment().format('lll'); // Feb 10, 2021 2:32 AM moment().format('LLLL'); // Wednesday, February 10, 2021 2:32 AM moment().format('llll'); // Wed, Feb 10, 2021 2:32 AM

한글 표기

import moment from 'moment'; import 'moment/locale/ko'; // <-- 이 줄을 추가로 명시하면 됨.

추가 사용 예시

moment("2015-01-01").startOf('day') .seconds(s) .format('H:mm:ss');

toNow

moment(Props.dueDate, 'YYYY-MM-DD hh:mm').toNow(); moment([2007, 0, 29]).toNow(); // in 4 years