如何在JavaScript中获取当前时间戳

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 on Date. Look for a polyfill if you need to support IE8 and below, or use new Date().getTime() if Date.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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值