moment常用操作

Moment.js 是一个 JavaScript 日期处理类库,用于解析、检验、操作、以及显示日期

日期格式化

1
2
3
4
5
moment().format('MMMM Do YYYY, h:mm:ss a'); // 九月 23日 2020, 11:31:24 中午
moment().format('dddd'); // 星期三
moment().format("MMM Do YY"); // 9月 23日 20
moment().format('YYYY [escaped] YYYY'); // 2020 escaped 2020
moment().format(); // 2020-09-23T11:31:24+08:00

相对时间

1
2
3
4
5
moment("20111031", "YYYYMMDD").fromNow(); // 9 年前
moment("20120620", "YYYYMMDD").fromNow(); // 8 年前
moment().startOf('day').fromNow(); // 12 小时前
moment().endOf('day').fromNow(); // 12 小时内
moment().startOf('hour').fromNow(); // 31 分钟前

日历时间

1
2
3
4
5
6
7
8
moment().subtract(10, 'days').calendar(); // 2020/09/13
moment().subtract(6, 'days').calendar(); // 上星期四11:31
moment().subtract(3, 'days').calendar(); // 上星期日11:31
moment().subtract(1, 'days').calendar(); // 昨天11:31
moment().calendar(); // 今天11:31
moment().add(1, 'days').calendar(); // 明天11:31
moment().add(3, 'days').calendar(); // 下星期六11:31
moment().add(10, 'days').calendar(); // 2020/10/03

多语言支持

1
2
3
4
5
6
7
8
9
10
11
moment.locale();         // zh-cn
moment().format('LT'); // 11:31
moment().format('LTS'); // 11:31:24
moment().format('L'); // 2020/09/23
moment().format('l'); // 2020/9/23
moment().format('LL'); // 2020年9月23日
moment().format('ll'); // 2020年9月23日
moment().format('LLL'); // 2020年9月23日中午11点31分
moment().format('lll'); // 2020年9月23日 11:31
moment().format('LLLL'); // 2020年9月23日星期三中午11点31分
moment().format('llll'); // 2020年9月23日星期三 11:31

操作计算

add

1
2
3
4
5
6
7
8
9
10
11
12
moment().add(7, 'days');
// 如果对希望简短,也有一些快捷的键。
moment().add(7, 'd');
// years -> y
// quarters -> Q
// months -> M
// weeks -> w
// days -> d
// hours -> h
// minutes -> m
// seconds -> s
// milliseconds -> ms