在 JavaScript 簡單取得 unix timestamp
我們經常需要計算 unix 的 timestamp。有許多方式可以取得 timestamp。目前取得 unix timestamp 最簡單和快速的方式是:
const dateTime = Date.now();
const timestamp = Math.floor(dateTime / 1000);
或
const dateTime = new Date().getTime();
const timestamp = Math.floor(dateTime / 1000);
如果要取得特定的 unix timestamp 傳送一個 YYYY-MM-DD
或 YYYY-MM-DDT00:00:00Z
參數到 Date
的建構子。例如:
const timestamp = new Date('2012-06-08').getTime()
當你宣告一個 Date
物件,也可以加上 +
符號:
const dateTime = +new Date();
const timestamp = Math.floor(dateTime / 1000);
或指定日期
const dateTime = +new Date('2012-06-08');
const timestamp = Math.floor(dateTime / 1000);
在執行時呼叫了 Date
物件的 valueOf
方法。+
運算子呼叫了 toNumber()
和回傳的值。更多細節的說明請參考以下的連結。
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW