Cyan Hall C H
CyanHall.com 创建。上次更新:11/25/2020 👉   现在官方也不再推荐使用 Moment.js,因此我制作了一个速查表,帮助你从 Moment.js 中迁移出来。 以下是一些 JavaScript 流行的日期/时间处理库:
  • Moment.js
    • Github 星数: 44.9k
    • min.js 58.9 kB (版本: 2.28.0)
  • Day.js
    • Github 星数: 29.5k
    • min.js 6 kB (版本: 1.8.26)
  • date-fns
    • Github 星数: 23.6k
    • 一个函数一个文件的风格

日期时间格式

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
ZZXXX+08:00
(Timezone)
ddddddcccThu
(Weekday)
ddddddddiiiiTuesday
(Weekday)
MMMMMMMMMSep
(Month)
DDd1..31
(Month Day)
SSSSSSSSS000..999
(Milliseconds)
Xunix()t1600357502
(Unix timestamp)
xvalueOf()T1600357502945
(Millisecond Unix timestamp)
Full docsFull docsFull docs


1. 安装

    npm install moment --save
  

2. 当前日期时间

    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
  

3. 解析日期时间

    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>
  

4. I18n

    moment.locale("zh-cn")
let current = moment().format("MMM")
console.log(current)
// 9月
  

5. 比较

    let oldDate = moment("09/17/2020", "MM/DD/YYYY")
let current = moment()
console.log(oldDate < current)
// true
  

6. 加 / 减

    // 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>
  

7. 开始 / 结束

    // 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>
  

8. 对比日期时间(diff)

    // 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