检测当前日期和时间现在在 Javascript 中的时间
我试图找出当前时间和日期是否等于来自 API 的日期。
api数据采用以下格式: 2021-01-02T08:00:00+01:00
我当前拥有的代码是:
if (new Date() === new Date(apiData) {
alert('its the current time accurate to seconds')
}
问题是我不认为这考虑到了不同的时区,我只想如果时间与 api 中的时间完全相同,则运行代码,无论客户端来自何处。
Im trying to find if the current time and date is equal to a date coming from an API.
The api data is in the following format: 2021-01-02T08:00:00+01:00
The code i currently have is:
if (new Date() === new Date(apiData) {
alert('its the current time accurate to seconds')
}
The problem is that i don't think that this takes in account different timezones, I only want to run the code if the time is exactly as the one from api, no matter where the client is coming from.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
时间戳 2021-01-02T08:00:00+01:00 代表一个独特的时刻。如果根据 ECMA-262 进行解析,它将生成一个时间值,该值是距 ECMAScript 纪元的毫秒偏移量:1970-01-01T00:00:00Z。
生成的时间值与主机系统设置无关,即主机偏移没有影响。因此:
在符合 ECMA-262 的每个实现中都会产生完全相同的值 (1609570800000)。
如果传递给 Date 构造函数,时间戳将以完全相同的方式进行解析,时间值用于 Date 实例,如下所示:
正如注释中提到的,ECMAScript 时间值具有毫秒精度,因此上述情况的机会return true 的值极小。将精度降低到一秒(例如通过四舍五入或截断小数秒)不会有太大帮助。
如果你想在时间戳指示的时间运行一些代码,你最好计算出剩余的时间,如果是将来的时间,设置一个超时,例如
:
请注意,在上面,第一个显示的时间戳将为 +1,第二个显示的时间戳为 +0,因此它们将相差 1 小时。
超时不一定在指定的时间之后运行。不过上面好像就是几毫秒。据我所知,超时的准确性(基于系统时钟)并不取决于延迟的长度,而是取决于延迟结束时系统的繁忙程度。
The timestamp 2021-01-02T08:00:00+01:00 represents a unique moment in time. If parsed according to ECMA-262, it will produce a time value that is a millisecond offset from the ECMAScript epoch: 1970-01-01T00:00:00Z.
The generated time value is independent of host system settings, i.e. the host offset has no effect. So:
will produce exactly the same value (1609570800000) in every implementation consistent with ECMA-262.
If passed to the Date constructor, the timestamp will be parsed in exactly the same way, with the time value being used for a Date instance such that:
As mentioned in comments, ECMAScript time values have millisecond precision, so the chance that the above will return true is extremely small. Reducing precision to one second (say by rounding or truncating the decimal seconds) won't help much.
If you want to run some code at the time indicated by the timestamp, you are best to work out the time left and, if it's in the future, set a timeout, something like:
E.g.
Note that in the above, the first displayed timestamp will be +1, the second +0 so they will be 1 hour different.
Timeouts don't necessarily run after exactly the time specified. However, the above seems to be a few milliseconds. As far as I know, the accuracy of the timeout (based on the system clock) isn't dependent on the length of the delay but on how busy the system is when it's elapsed.
使用此代码
Use This Code