简单获取unix时间戳
我们经常需要使用unix时间戳计算。有很多方法可以取得unix时间戳。目前取得unix时间戳最简单最快的方法是:
const dateTime = Date.now();
const timestamp = Math.floor(dateTime / 1000);
或
const dateTime = new Date().getTime();
const timestamp = Math.floor(dateTime / 1000);
要取得一个具体时间的unix时间戳,将yyyy-mm-dd
或YYYY-MM-DDT00:00:00Z
作为参数传递给Date
构造函数。例如
const dateTime = new Date('2012-06-08').getTime();
const timestamp = Math.floor(dateTime / 1000);
你还可以像下面一样,在声明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