Created by CyanHall.com
on 11/08/2020
, Last updated: 04/30/2021.
πΒ Β Star me if itβs helpful. Since Moment.js is not recommended by official, here is a cheatsheet may help you migrate from it. Here are some popular libraries that manipulates Date and Time in javascript:
πΒ Β Star me if itβs helpful. Since Moment.js is not recommended by official, here is a cheatsheet may help you migrate from it. Here are some popular libraries that manipulates Date and Time in javascript:
Date Time Format
Moment.js | Day.js | date-fns | Example |
---|---|---|---|
MM/DD/YYYY HH:mm:ss | MM/DD/YYYY HH:mm:ss | MM/dd/yyyy HH:mm:ss | 09/17/2020 23:45:02 |
Z | Z | XXX | +08:00 (Timezone) |
ddd | ddd | ccc | Thu (Weekday) |
dddd | dddd | iiii | Tuesday (Weekday) |
MMM | MMM | MMM | Sep (Month) |
D | D | d | 1..31 (Month Day) |
SSS | SSS | SSS | 000..999 (Milliseconds) |
X | unix() | t | 1600357502 (Unix timestamp) |
x | valueOf() | T | 1600357502945 (Millisecond Unix timestamp) |
Full docs | Full docs | Full docs |
1. Install
npm install moment --save
3. Parse Datetime
let formatStr = "MM/DD/YYYY HH:mm:ss"
let dateStr = "09/17/2020 23:45:02"
let current = moment(dateStr, formatStr)
console.log(current)
// Moment<2020-09-17T23:45:02+08:00>
5. Compare
let oldDate = moment("09/17/2020", "MM/DD/YYYY")
let current = moment()
console.log(oldDate < current)
// true
7. StartOf / EndOf
// second, minute, hour, day, week, month, year
let start = moment().startOf("day")
console.log(start)
// Moment<2020-09-18T00:00:00+08:00>
let end = moment().endOf("month")
console.log(end)
// Moment<2020-09-30T23:59:59+08:00>
2. Current Datetime
import moment from 'moment'
let formatStr = "MM/DD/YYYY HH:mm:ss"
let current = moment().format(formatStr)
console.log(current)
// 09/17/2020 23:45:02
4. I18n
moment.locale("zh-cn")
let current = moment().format("MMM")
console.log(current)
// 9ζ
6. Add / Subtract
// seconds, minutes, hours, days, weeks, months, years
let tormorow = moment().add(1, "days")
console.log(tormorow)
// Moment<2020-09-19T17:33:36+08:00>
let lastWeek = moment().subtract(1, "weeks")
console.log(lastWeek)
// Moment<2020-09-11T17:35:10+08:00>
let nextMonth = moment().add(1, "months")
console.log(nextMonth)
// Moment<2020-10-18T17:35:40+08:00>
8. diff date
// seconds, minutes, hours, days, weeks, months, years
let date1 = moment("01/01/2018", "MM/DD/YYYY")
let date2 = moment()
console.log(date1.diff(date2, 'days'))
// -991
console.log(date1.diff(date2, 'years'))
// -2
More