1. 日期格式不能直接判断相等(年-月-日)但可以比较大小。
const d1 = new Date('2019-06-01');
const d2 = new Date('2018-06-01');
const d3 = new Date('2019-06-01');
d1 === d3; // false
d1 == d3; // false
判断方式:用toString()或者valueOf()。
日期对象的toString()方法将日期转成 ISO 日期字符串形式,valueOf() 方法则将日期转成毫秒数字形式的时间戳。
const d1 = new Date('2019-06-01');
const d2 = new Date('2018-06-01');
const d3 = new Date('2019-06-01');
d1.toString(); // Sat Jun 01 2019 08:00:00 GMT+0800 (中国标准时间)
d1.valueOf(); // 1559347200000
d1.toString() === d2.toString(); // false
d1.toString() === d3.toString(); // true
d1.valueOf() === d2.valueOf(); // false
d1.valueOf() === d3.valueOf(); // true
比较大小:
d1 < d2; // false
d1 < d3; // false
d2 < d1; // true
求时间差:
const d1 = new Date('2019-06-01');
const d2 = new Date('2018-06-01');
const d3 = new Date('2019-06-01');
d1 - d3; // 0
d1 - d2; // 1 年的毫秒数, 1000 * 60 * 60 * 24 * 365
2. 日期排序
const d1 = new Date('2017-06-01');
const d2 = new Date('2018-06-01');
const d3 = new Date('2019-06-01');
[d2, d1, d3].sort(); // [d2, d3, d1]
sort排序不稳定,是基于ASCII进项排序的。实际排序是变为ISO进行排序。
[ 'Fri Jun 01 2018 08:00:00 GMT+0800 (中国标准时间)',
'Sat Jun 01 2019 08:00:00 GMT+0800 (中国标准时间)',
'Thu Jun 01 2017 08:00:00 GMT+0800 (中国标准时间)' ]
可以在sort排序中 添加一个自定义排序。
0 表示 a 和b 相等
正值表示 a > b,也就是a在b后面
负值表示 a < b,也就是a在b前面
const d1 = new Date('2017-06-01');
const d2 = new Date('2018-06-01');
const d3 = new Date('2019-06-01');
[d2, d1, d3].sort((a, b) => a - b); // [d1, d2, d3]
数组也可以这样排序。
const a = [1, 4, 3, 12];
a.sort(); // [1, 12, 3, 4]