자바스크립트/library
Moment.js를 이용하여 시간 차이를 구하는 방법
Socratone
2021. 8. 2. 21:51
moment에 특정 시간을 설정하려면 아래와 같이 시간을 나타내는 규격화된 형태의 문자를 인자로 넣어야 한다.
const time = moment('2021-12-24 12:00:01');
// 경우에 따라서 두 번째 인자를 추가해 첫 번째 인자의 format을 명시해주기도 해야 한다.
// moment('2021-12-24 12:00:01', 'YYYY-MM-DD hh:mm:ss')
24일 12시 1초와 25일 12시 1초의 시간 차이를 구해야 한다고 해보자.
먼저 앞의 시간과 뒤의 시간을 moment로 정의해야 한다.
import moment from 'moment';
const time1 = moment('2021-12-24 12:00:01'); // 24일 12시 1초
const time2 = moment('2021-12-25 12:00:01'); // 25일 12시 1초
time1과 time2의 시간 차이를 구하려면 duration 메소드를 쓴다.
일(day) 차이를 계산하고 싶으면
moment.duration(time2.diff(time1)).asDays() // 1
시간(hour) 차이를 계산하고 싶으면
moment.duration(time2.diff(time1)).asHours() // 24
분(minute) 차이를 계산하고 싶으면
moment.duration(time2.diff(time1)).asMinutes() // 1440
초(second) 차이를 계산하고 싶으면
moment.duration(time2.diff(time1)).asSeconds() // 86400