wisetc / practice

Practice conclusion
5 stars 0 forks source link

获取今天的时间戳 #25

Open wisetc opened 5 years ago

wisetc commented 5 years ago

情景复现

截取时间日期字符串中的日期部分,然后构造 Date 对象,最后输出的结果不是想要的结果,例如,

// 下面的这个时间是错误的,
// 原因待探讨
> d = new Date()
> new Date(d.toISOString().slice(0, 10)).getTime()

思考

到底是截取去掉的时间不正确还是 Date 构造函数输入的值不正确,于是引出一个问题,“实例一个 Date 对象,参数形式不同,会有相同的结果吗?”如下示例:

// 在东八区,输出 false
new 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);
});
wisetc commented 4 years ago

构造函数创建Date对象,若参数形式为字符串会先隐式调用 Date.parse 解析并认为字符串是标准时间格式,使用GMT+0,而当参数形式为数字多参时,则会采用系统对应的时区,实验中为GMT+8,故二者结果不一样。

wisetc commented 4 years ago

function today() {
  const d = new Date();
  d.setHours(0, 0, 0, 0);
  return d.getTime();
}