Skip to content

Moment.js

介绍

Moment.js 是一个 JavaScript 日期库,用于解析、验证、作日期和设置日期格式。

提示

推荐替代方案:Day.jsdate-fns ……

创建时间

js
moment() // 当前时间
moment('2025-06-15') // 指定日期
moment('2025-06-15 12:30', 'YYYY-MM-DD HH:mm') // 指定格式
moment([2025, 5, 15]) // 注意:月份从0开始(6月是5)
moment.unix(1718448000) // Unix 时间戳(秒)

格式化时间

js
moment().format() // 默认格式:2025-06-15T12:34:56+08:00
moment().format('YYYY-MM-DD') // 2025-06-15
moment().format('YYYY年MM月DD日 HH:mm') // 2025年06月15日 12:30

常见格式符:

符号含义示例
YYYY年(四位)2025
YY年(两位)25
MM月(补 0)06
M月(不补 0)6
DD日(补 0)09
D日(不补 0)9
HH / hh24/12 小时(补 0)14 / 02
H / h24/12 小时(不补 0)14 / 2
mm / ss分钟/秒(补 0)09 / 45
m / s分钟/秒(不补 0)9 / 5
A / a上午/下午(AM/PM)AM / am
d / dd / ddd / dddd星期(日)0 / Su / Sun / Sunday

获取时间信息

js
moment().year() // 年
moment().month() // 月(0-11)
moment().date() // 日
moment().hour() // 时
moment().minute() // 分
moment().second() // 秒
moment().day() // 星期(0是星期天)

时间运算

js
moment().add(3, 'days') // 加三天
moment().subtract(1, 'month') // 减一个月
moment().startOf('month') // 月初
moment().endOf('day') // 当天结束

可用单位:years, months, weeks, days, hours, minutes, seconds, milliseconds

时间比较

js
moment('2025-06-15').isBefore('2025-07-01') // true
moment().isAfter('2024-01-01') // true
moment().isSame('2025-06-15', 'day') // 是否同一天

⏱ 时间差计算

js
const a = moment('2025-06-15')
const b = moment('2025-07-01')

b.diff(a, 'days') // 16
b.diff(a, 'hours') // 384

本地化支持(中文)

js
moment.locale('zh-cn')

moment().format('LLLL') // 2025年6月15日星期日 12:30
moment().fromNow() // 几秒前
moment().calendar() // 今天12:30

转换与解析

js
moment().toDate() // 转为原生 Date 对象
moment().toISOString() // 转为 ISO 字符串
moment().unix() // 转为 Unix 时间戳(秒)
moment().valueOf() // 转为毫秒时间戳
moment('2025-06-15').toJSON() // JSON 序列化

基于 MIT 许可发布