我试图将当前的UTC日期存储在我的数据库中.我当地时间是下午9:11这相当于UTC时间上午1:11.当我查看我的数据库时,我注意到下午1:11正在写入.我糊涂了.为了在JavaScript中获取UTC时间,我使用以下代码:
var currentDate = new Date();
var utcDate = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds(), currentDate.getMilliseconds());
var result = new Date(utcDate);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
经过一番搜索发现你可以这样做:
var now = new Date(),
utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
Run Code Online (Sandbox Code Playgroud)
甚至更短:
var utcDate = new Date(new Date().toUTCString().substr(0, 25));
Run Code Online (Sandbox Code Playgroud)
这是一种常用的方法,而不是创建 ISO8601 字符串,来获取 UTC 的日期和时间。因为如果您使用字符串,那么您将无法使用 的每一个本机方法Date()
,并且有些人可能会使用正则表达式,这比本机方法慢。
但是,如果您将其存储在某种数据库中localstorage
,例如 ,建议使用 ISO8601 字符串,因为它还可以保存时区偏移量,但在您的情况下,每个date
都会转换为 UTC,因此时区实际上并不重要。
归档时间: |
|
查看次数: |
2861 次 |
最近记录: |