The UNIX timestamp is an integer that represents the number of seconds elapsed since January 1 1970.
UNIX时间戳是一个整数,表示自1970年1月1日以来经过的秒数 。
On UNIX-like machines, which include Linux and macOS, you can type date +%s
in the terminal and get the UNIX timestamp back:
在包括Linux和macOS的类似UNIX的计算机上,可以在终端中键入date +%s
并获取UNIX时间戳:
$ date +%s
1524379940
The current timestamp can be fetched by calling the now()
method on the Date
object:
可以通过在Date
对象上调用now()
方法来获取当前时间戳:
Date. now ()
You could get the same value by calling
您可以通过致电获得相同的价值
new Date(). getTime ()
or
new Date(). valueOf ()
Note: IE8 and below do not have the
now()
method onDate
. Look for a polyfill if you need to support IE8 and below, or usenew Date().getTime()
ifDate.now
is undefined (as that’s what a polyfill would do)注意:IE8及以下版本在
Date
上没有now()
方法。 如果需要支持IE8及以下版本,请寻找一个Date.now
;如果未定义Date.now
,请使用new Date().getTime()
(因为那是Date.now
方式)
The timestamp in JavaScript is expressed in milliseconds.
JavaScript中的时间戳以毫秒表示。
To get the timestamp expressed in seconds, convert it using:
要获取以秒为单位的时间戳,请使用以下命令进行转换:
Math. floor (Date. now () / 1000 )
Note: some tutorials use
Math.round()
, but that will approximate to the next second even if the second is not fully completed.注意:有些教程使用
Math.round()
,但是即使第二秒没有完全完成,它也会接近下一秒。
or, less readable:
或者,可读性较差:
~~ (Date. now () / 1000 )
I’ve seen tutorials using
我看过使用教程
+ new Date
which might seem a weird statement, but it’s perfectly correct JavaScript code. The unary operator + automatically calls the valueOf()
method on any object it is assigned to, which returns the timestamp (in milliseconds). The problem with this code is that you instantiate a new Date object that’s immediately discarded.
这可能看起来很怪异,但这是完全正确JavaScript代码。 一元运算符+在分配给它的任何对象上自动调用valueOf()
方法,该方法返回时间戳(以毫秒为单位)。 此代码的问题是,您实例化了一个立即被丢弃的新Date对象。
To generate a date from a timestamp, use new Date(<timestamp>)
but make sure you pass a number (a string will get you an “invalid date” result - use parseInt()
in doubt)
要从时间戳生成日期,请使用new Date(<timestamp>)
但要确保您传递一个数字(字符串将为您提供“无效日期”结果-请使用有疑问的parseInt()
)
翻译自: https://flaviocopes.com/how-to-get-timestamp-javascript/