Moment.js的常用方法

安装与引用

官方文档

安装

1
npm install moment --save

引用

1
2
import moment from 'moment';
var moment = require('moment');

自定义配置

获取当前语言

1
moment.locale();

加载语言

1
moment.locale('zh-cn');

UTC

获取UTC

1
moment().utc();

UTC偏移量

1
moment().utcOffset();

设置偏移量

以下是相同的

1
2
3
moment().utcOffset("+08:00");
moment().utcOffset(8);
moment().utcOffset(480);

Moment和Date

相互转换

Date ==> Moment

1
moment(new Date())

Moment ==> Date

1
moment().toDate()

是否 Moment 对象

1
2
3
moment.isMoment() // false
moment.isMoment(new Date()) // false
moment.isMoment(moment()) // true

是否 Date 对象

1
2
3
moment.isDate(); // false
moment.isDate(new Date()); // true
moment.isDate(moment()); // false

验证日期格式是否正确

1
moment("not a real date").isValid(); // false

初始化日期

字符串

1
var day = moment("1995-12-25");

支持一下格式

1
2
3
4
5
6
2013-02-08T09            # An hour time part separated by a T
2013-02-08 09 # An hour time part separated by a space
2013-02-08 09:30 # An hour and minute time part
2013-02-08 09:30:26 # An hour, minute, and second time part
2013-02-08 09:30:26.123 # An hour, minute, second, and millisecond time part
2013-02-08 24:00:00.000 # hour 24, minute, second, millisecond equal 0 means next day at midnight

字符串+格式化

1
moment("12-25-1995", "MM-DD-YYYY");

对象方式

1
2
3
4
5
moment({ hour:15, minute:10 });
moment({ y:2010, M:3, d:5, h:15, m:10, s:3, ms:123});
moment({ year :2010, month :3, day :5, hour :15, minute :10, second :3, millisecond :123});
moment({ years:2010, months:3, days:5, hours:15, minutes:10, seconds:3, milliseconds:123});
moment({ years:2010, months:3, date:5, hours:15, minutes:10, seconds:3, milliseconds:123});

Unix 偏移量(毫秒)

1
var day = moment(1318781876406);

取值

1
moment().valueOf();

Unix 时间戳(秒)

1
var day = moment.unix(1318781876);

取值

1
moment().unix();

Date对象

1
2
var day = new Date(2011, 9, 16);
var dayWrapper = moment(day);

数组

1
2
3
4
moment([2010, 1, 14, 15, 25, 50, 125]);
moment([2010]);
moment([2010, 6]);
moment([2010, 6, 10]);

日期转字符串

比如

1
2
3
4
5
moment().format();                                // "2014-09-08T08:02:17-05:00" (ISO 8601)
moment().format("YYYY-MM-DD HH:mm:ss"); // "2014-09-08 14:17:10"
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA"); // "Sun, 3PM"
moment('gibberish').format('YYYY MM DD'); // "Invalid date"

排除字符

1
moment().format('[today] dddd'); // 'today Sunday'

格式化字符串

Token Output
Month M 1 2 … 11 12
Mo 1st 2nd … 11th 12th
MM 01 02 … 11 12
MMM Jan Feb … Nov Dec
MMMM January February … November December
Quarter Q 1 2 3 4
Day of Month D 1 2 … 30 31
Do 1st 2nd … 30th 31st
DD 01 02 … 30 31
Day of Year DDD 1 2 … 364 365
DDDo 1st 2nd … 364th 365th
DDDD 001 002 … 364 365
Day of Week d 0 1 … 5 6
do 0th 1st … 5th 6th
dd Su Mo … Fr Sa
ddd Sun Mon … Fri Sat
dddd Sunday Monday … Friday Saturday
Day of Week (Locale) e 0 1 … 5 6
Day of Week (ISO) E 1 2 … 6 7
Week of Year w 1 2 … 52 53
wo 1st 2nd … 52nd 53rd
ww 01 02 … 52 53
Week of Year (ISO) W 1 2 … 52 53
Wo 1st 2nd … 52nd 53rd
WW 01 02 … 52 53
Year YY 70 71 … 29 30
YYYY 1970 1971 … 2029 2030
Week Year gg 70 71 … 29 30
gggg 1970 1971 … 2029 2030
Week Year (ISO) GG 70 71 … 29 30
GGGG 1970 1971 … 2029 2030
AM/PM A AM PM
a am pm
Hour H 0 1 … 22 23
HH 00 01 … 22 23
h 1 2 … 11 12
hh 01 02 … 11 12
Minute m 0 1 … 58 59
mm 00 01 … 58 59
Second s 0 1 … 58 59
ss 00 01 … 58 59
Fractional Second S 0 1 … 8 9
SS 00 01 … 98 99
SSS 000 001 … 998 999
SSSS … SSSSSSSSS 000[0..] 001[0..] … 998[0..] 999[0..]
Timezone z or zz EST CST … MST PST Note: as of 1.6.0, the z/zz format tokens have been deprecated.
Z -07:00 -06:00 … +06:00 +07:00
ZZ -0700 -0600 … +0600 +0700
Unix Timestamp X 1360013296
Unix Millisecond Timestamp x 1360013296123

取值/赋值

日期和时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 毫秒
moment().milliseconds(Number);
moment().milliseconds(); // Number
// 秒
moment().seconds(Number);
moment().seconds(); // Number
// 分钟
moment().minutes(Number);
moment().minutes(); // Number
// 小时
moment().hours(Number);
moment().hours(); // Number
// 日期
moment().dates(Number);
moment().dates(); // Number

年月日时分秒

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 取值
moment().get('year');
moment().get('month'); // 0 to 11
moment().get('date');
moment().get('hour');
moment().get('minute');
moment().get('second');
moment().get('millisecond');
// 赋值
moment().set('year', 2013);
moment().set('month', 3); // April
moment().set('date', 1);
moment().set('hour', 13);
moment().set('minute', 20);
moment().set('second', 30);
moment().set('millisecond', 123);

moment().set({'year': 2013, 'month': 3});

星期的取值和赋值

周日为0

周六为6

1
2
3
4
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)

注意:

因为计算的时候会把周日作为一周的第一天,所以我们要判断周日的情况

周一

1
2
3
4
5
let date = moment("2022-12-11");
let weekOfDay = date.day();
let monDay = date.day(1).hours(0).minutes(0).seconds(0)
monDay = weekOfDay === 0 ? monDay.subtract(7, "days") : monDay;
console.info(monDay.format("YYYY-MM-DD HH:mm:ss"));

周日

1
2
3
4
5
let date = moment("2022-12-11");
let weekOfDay = date.day();//0的时候为周日
let sunDay = date.day(7).hours(23).minutes(59).seconds(59)
sunDay = weekOfDay === 0 ? sunDay.subtract(7, "days") : sunDay;
console.info(sunDay.format("YYYY-MM-DD HH:mm:ss"));

按区域标准

1
2
3
// 比如周一是一星期的第一天
moment().weekday(-7); // last Monday
moment().weekday(7); // next Monday

这种方式 获取本周一

跟预想的不一样,并没有和区域标准一样,不建议

1
2
3
4
5
6
7
let date = moment("2022-12-11");
let weekOfDay = date.weekday();
let mon = date.weekday(1).hours(0).minutes(0).seconds(0);
if (weekOfDay === 0) {
mon = mon.subtract(7, "days");
}
console.info(mon.format("YYYY-MM-DD HH:mm:ss"));

时间操作

Key Shorthand
years y
quarters Q
months M
weeks w
days d
hours h
minutes m
seconds s
milliseconds ms

加法

1
2
3
4
moment().add(15, 'minutes')
moment().add(7, 'days').add(1, 'months'); // with chaining
moment().add(7, 'd');
moment().add({days:7,months:1}); // with object literal

减法

1
moment().subtract(7, 'days');

比较

1
2
3
4
5
6
7
8
9
10
//之前
moment('2010-10-20').isBefore('2010-10-21'); // true
//相同
moment('2010-10-20').isSame('2010-10-20'); // true
//之后
moment('2010-10-20').isAfter('2010-10-19'); // true
//之间
moment('2010-10-20').isBetween('2010-10-19', '2010-10-25'); // true
// 是否闰年
moment().isLeapYear();

差值

1
2
3
4
5
moment(this.endTime).diff(moment(this.startTime), 'years')
moment(this.endTime).diff(moment(this.startTime), 'months')
moment(this.endTime).diff(moment(this.startTime), 'days')
moment(this.endTime).diff(moment(this.startTime),'minutes' )
moment(this.endTime).diff(moment(this.startTime), 'seconds')

返回浮点数

1
moment(item2.startDate).diff(this.startTime, "minutes", true)

对象克隆

1
2
3
4
var a = moment([2012]);
var b = moment(a);
a.year(2000);
b.year(); // 2012

或者

1
2
3
4
var a = moment([2012]);
var b = a.clone();
a.year(2000);
b.year(); // 2012