Moment.js Cheatsheet - Date & Time

Moment.js 日期处理必备 API 都在这里了,从日期创建到格式化操作,按类别分类整理,写代码时直接复制。

Languages·39 commands·Last updated 2026-07-21
Back to Languages

创建日期 5

moment()
当前时间
moment("2024-01-15")
从字符串解析
moment("2024-01-15", "YYYY-MM-DD")
指定格式解析
moment(Date.now())
从时间戳创建
moment({ year: 2024, month: 0, day: 15 })
从对象创建

格式化 5

moment().format("YYYY-MM-DD")
2024-01-15
moment().format("HH:mm:ss")
14:30:00
moment().format("dddd, MMMM Do YYYY")
Monday, January 15th 2024
moment().format("LLL")
本地化长格式
moment().toISOString()
ISO 8601 格式

操作日期 5

moment().add(7, "days")
加 7 天
moment().subtract(1, "month")
减 1 个月
moment().startOf("day")
设置为当天 00:00:00
moment().endOf("month")
设置为月末 23:59:59
moment().year(2025).month(0)
设置年月

查询与比较 8

moment().isBefore(other)
是否在之前
moment().isAfter(other)
是否在之后
moment().isSame(other, "day")
是否同一天
moment().isBetween(start, end)
是否在区间内
moment().isSameOrBefore(other)
相同或之前
moment().isSameOrAfter(other)
相同或之后
moment().diff(other, "days")
计算差值(指定单位)
moment().isValid()
是否有效日期

相对时间 6

moment().fromNow()
3 天前
moment().fromNow(true)
3 天(不含"前")
moment().toNow()
3 天后
moment().calendar()
今天 14:30 / 昨天 09:00
moment().from(other)
相对另一时刻的偏移
moment().to(other)
到另一时刻的偏移

时区与本地化 5

moment().utc()
转为 UTC 时间
moment().local()
转为本地时间
moment.locale("zh-cn")
设置中文
moment.tz("2024-01-15", "America/New_York")
指定时区(需 moment-timezone)
moment().utcOffset(480)
设置 UTC 偏移(分钟)

Duration 时长 5

moment.duration(100, "minutes")
从分钟创建时长
moment.duration({ hours: 2, minutes: 30 })
从对象创建时长
duration.asHours()
转换为总小时数
duration.humanize()
人性化显示(如"2 小时")
duration.add(1, "hour")
时长加运算

💡 Tips

  • Moment.js 已停止新功能开发,新项目推荐 dayjs(API 兼容,体积更小)。
  • 月份从 0 开始:0=一月,11=十二月。
  • format 令牌:YYYY=年,MM=月,DD=日,HH=时,mm=分,ss=秒。
  • 操作日期会返回新 moment 对象,原对象不可变。
  • fromNow/toNow 自动选择单位(秒、分钟、小时、天、月、年)。
  • diff 默认返回毫秒,传入第二参数可指定单位(days/months/years)。
  • duration 用于度量时间长度而非某个时间点,humanize 可输出友好文本。