在 javascript 中獲取當前時間有兩種方法:使用 date 對象:date.now() 返回當前時間的時間戳(毫秒)。date() 創(chuàng)建一個代表當前時間的 date 對象。使用 performance api:performance.now() 返回高分辨率的時間戳(毫秒)。
JS獲取當前時間
在JavaScript中,獲取當前時間可以使用Date對象或performance API。
使用Date對象
最簡單的方法是使用Date對象,它提供了以下方法:
Date.now():返回當前時間的時間戳,單位為毫秒。
Date():創(chuàng)建一個新的Date對象,代表當前時間。
代碼示例:
// 獲取當前時間戳 const timestamp = Date.now(); // 創(chuàng)建一個代表當前時間的Date對象 const date = new Date();
登錄后復制
使用performance API
performance API提供了更精確的時間測量功能。它有一個名為now()的方法,可以返回當前時間的高分辨率時間戳,單位為毫秒。
代碼示例:
// 獲取當前高分辨率時間戳 const timestamp = performance.now();
登錄后復制
選擇合適的方法
對于大多數(shù)情況下,使用Date.now()就足夠了。但是,如果你需要高精度的計時,可以使用performance.now()。
注意:
時間戳是自1970年1月1日00:00:00 UTC以來的毫秒數(shù)。
不同的瀏覽器可能對performance.now()有不同的實現(xiàn),因此其精度可能會有所不同。