js 獲取今天的時間戳

情景復現

截取時間日期字符串中的日期部分,而後構造 Date 對象,最後輸出的結果不是想要的結果,例如,函數

// 下面的這個時間是錯誤的,
// 緣由待探討
> d = new Date()
> new Date(d.toISOString().slice(0, 10)).getTime()

思考

究竟是截取去掉的時間不正確仍是 Date 構造函數輸入的值不正確,因而引出一個問題,「實例一個 Date 對象,參數形式不一樣,會有相同的結果嗎?」以下示例:code

// 在東八區,輸出 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);
});
相關文章
相關標籤/搜索