Hi,
請問一個時間字串(e.g.2021-01-18T07:47:21.273Z)想要與目前時間做比較並且得到相差秒數, 該如何處理?
var t1 = new Date("2021-01-18T07:47:21.273Z");
t1 = Math.floor(t1 / 1000);
const dateTime = Date.now();
const t2 = Math.floor(dateTime / 1000);
Z結尾代表是 UTC
可以用 Date.UTC 取得 timestamp
const testStr='2021-01-18T07:47:21.273Z';
let arr=testStr.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):([0-9\.]+)Z$/);
if(!arr) {
throw new Error('格式錯誤');
}
arr=arr.slice(1).map(x=>parseFloat(x));
arr[1]--; //月份是從 0 開始
let t=Date.UTC.apply(null, arr);
console.log((Date.now()-t)/1000);