JavaScript 中的 UTC 时间
UTC Times in JavaScript
我正在尝试获取当前的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);
我做错了什么?
搜索结果可以做到这一点:
var now = new Date(),
utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
甚至更短:
var utcDate = new Date(new Date().toUTCString().substr(0, 25));
如何将 JavaScript 日期转换为 UTC?
这是一种常用的方法,而不是创建ISO8601字符串,以获取 UTC 的日期和时间。因为如果你使用字符串,那么你将无法使用每一个本机方法Date()
,有些人可能会为此使用正则表达式,这比本机方式慢。
但是,如果您将其存储在某种数据库中,例如 localstorage
,建议使用 ISO8601 字符串,因为它还可以保存时区偏移量,但在您的情况下,每个date
都转换为 UTC,因此时区真的无关紧要。
如果需要本地日期对象的 UTC 时间,请使用 UTC 方法获取它。所有 javascript 日期对象都是本地日期。
var date = new Date(); // date object in local timezone
如果你想要UTC时间,你可以尝试实现相关的toUTCString
方法:
var UTCstring = date.toUTCString();
但我不会相信这一点。如果你想要一个 UTC 时间的ISO8601字符串(大多数数据库都需要(,那么:
var isoDate = date.getUTCFullYear() + '-' +
addZ((date.getUTCMonth()) + 1) + '-' +
addZ(date.getUTCDate()) + 'T' +
addZ(date.getUTCHours()) + ':' +
addZ(date.getUTCMinutes()) + ':' +
addZ(date.getUTCSeconds()) + 'Z';
其中addZ
函数为:
function addZ(n) {
return (n<10? '0' : '') + n;
}
修改以适应。
编辑
要将本地日期对象调整为与 UTC 显示相同的时间,只需添加时区偏移量:
function adjustToUTC(d) {
d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
return d;
}
alert(adjustToUTC(new Date())); // shows UTC time but will display local offset
请注意上述内容。如果你说 UTC+5hrs,那么它将在 5 小时前返回一个日期对象,但仍显示"UTC+5">
用于将 UTC ISO8601字符串转换为本地日期对象的函数:
function fromUTCISOString(s) {
var b = s.split(/[-T:'.Z]/i);
var n= new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5]));
return n;
}
alert(fromUTCISOString('2012-05-21T14:32:12Z')); // local time displayed
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
相关文章:
- 将日期和时间转换为UTC格式的日期-Javascript
- javascript/jquery将utc转换为短格式的本地时间
- 将时间转换为UTC时出现故障
- 将日期和时间转换为UTC
- 如何在时间标签和相同的类中以UTC格式重新格式化ISO 8601时间戳,并通过JavaScript根据用户区域设置和时区
- 如何将 UTC 日期时间(字符串)转换为访问者时区
- 如何在javascript中获取正确的UTC时间
- 如何使用javascript在网络上仅将UTC时间戳转换为本地时间?从 http://openweathermap.or
- 时刻.js + 实时戳时间前基于 UTC 来自服务器的日期时间
- 如何转换SalesForce Api提供的UTC日期格式,并使用Google Apps脚本将其转换为本地日期和时间格式
- JavsScript:如何将UTC时间戳转换为人类可读时间
- 正在读取UTC时间字符串
- 在mirth connect中,将本地时间的hl7日期时间转换为UTC的iso日期
- javascript使jquery倒计时与UTC时间一起工作
- 将时区格式的日期显示为UTC时间
- Angularjs:带日期助手的格式化UTC时间的时间戳
- 用javascript将精度为17位的unix时间(UTC)转换为日期fromat
- 检查当前时间(UTC)是否在范围内
- 确定当天的开始和结束时间(UTC) (JAVASCRIPT)
- 从开始 - 结束日期和时间 (UTC) 计算出日期范围