情景复现
截取时间日期字符串中的日期部分,然后构造 Date 对象,最后输出的结果不是想要的结果,例如,
// 下面的这个时间是错误的,// 原因待探讨> d = new Date()> new Date(d.toISOString().slice(0, 10)).getTime()
思考
到底是截取去掉的时间不正确还是 Date 构造函数输入的值不正确,于是引出一个问题,“实例一个 Date 对象,参数形式不同,会有相同的结果吗?”如下示例:
// 在东八区,输出 falsenew Date(2019, 5, 5) === new Date('2019-06-05')
所以,日期控件输出,以及日期时间戳的计算,统一用标准时间格式。
// 今天的时间戳function today() { return moment().startOf('day').valueOf();}
test('today', () => { const todayTimestamp = today(); const nowDate = new Date(); const UTCFullYear = nowDate.getUTCFullYear(); const UTCMonth = nowDate.getUTCMonth(); const UTCDate = nowDate.getUTCDate(); const UTCTimestamp = new Date(UTCFullYear, UTCMonth, UTCDate).getTime(); expect(todayTimestamp).toEqual(UTCTimestamp);});