Moment.js Cheatsheet - Date & Time

All essential Moment.js commands organized by use case, with 39+ entries you can copy and run directly. Find the right command fast when you need it.

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

Create 5

moment()
当前时间
moment("2024-01-15")
从string解析
moment("2024-01-15", "YYYY-MM-DD")
指定格式解析
moment(Date.now())
从时间戳Create
moment({ year: 2024, month: 0, day: 15 })
从objectCreate

Format 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 格式

Manipulate 5

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

Query & Compare 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()
是否有效日期

Relative Time 6

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

Timezone & Locale 5

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

Duration 5

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

💡 Tips

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

Official References

Commands are compiled from the official docs below. Click to verify the latest usage.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Found an error? Report it

Wrong command or description? Open an issue to help us fix it.

Found an error? Report it