假设您网站的用户输入了一个日期范围。
2009-1-1 to 2009-1-3
您需要将此日期发送到服务器进行某些处理,但服务器要求所有日期和时间均为UTC。
现在假设用户在阿拉斯加。由于它们所处的时区与UTC完全不同,因此需要将日期范围转换为如下所示:
2009-1-1T8:00:00 to 2009-1-4T7:59:59
使用JavaScriptDate对象,如何将第一个“本地化”日期范围转换为服务器能够理解的内容?
假设您网站的用户输入了一个日期范围。
2009-1-1 to 2009-1-3
您需要将此日期发送到服务器进行某些处理,但服务器要求所有日期和时间均为UTC。
现在假设用户在阿拉斯加。由于它们所处的时区与UTC完全不同,因此需要将日期范围转换为如下所示:
2009-1-1T8:00:00 to 2009-1-4T7:59:59
使用JavaScriptDate对象,如何将第一个“本地化”日期范围转换为服务器能够理解的内容?
当前回答
var userdate = new Date("2009-1-1T8:00:00Z");
var timezone = userdate.getTimezoneOffset();
var serverdate = new Date(userdate.setMinutes(userdate.getMinutes()+parseInt(timezone)));
这将为您提供正确的UTC日期和时间。这是因为getTimezoneOffset()将以分钟为单位提供时区差异。我建议您不要使用toISOString(),因为输出将在字符串中。因此,将来您将无法操纵日期
其他回答
简单又愚蠢
var date=新日期();var now_utc=日期utc(Date.getUTCFullYear(),Date.getUTCMonth(),date.getUTCDate(),date.getUTPours(),date.getUTCMinutes(),date.getUTCSeconds());console.log(新日期(now_utc));console.log(date.toISOString());
我刚刚发现Steven Levithan的date.format.js的1.2.3版本正是我想要的。它允许您为JavaScript日期提供格式字符串,并将从本地时间转换为UTC。下面是我现在使用的代码:
// JavaScript dates don't like hyphens!
var rectifiedDateText = dateText.replace(/-/g, "/");
var d = new Date(rectifiedDateText);
// Using a predefined mask from date.format.js.
var convertedDate = dateFormat(d, 'isoUtcDateTime');
对于目标是将其作为“日期对象”而不是字符串获取的其他人,并且您只想显示不带TZ(可能是硬编码的)的日期/时间,您可以做的是:
const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
const hour = now.getUTCHours();
const tomorrowUTC= new Date();
tomorrowUTC.setDate(day + 1); // +1 because my logic is to get "tomorrow"
tomorrowUTC.setYear(year);
tomorrowUTC.setMonth(month);
tomorrowUTC.Hours(hour);
// then use the tomorrowUTC for to display/format it
// tomorrowUTC is a "Date" and not a string.
然后,您可以执行以下操作:
我们将在${格式(明天UTC,'EEEE do MMMM hh:mmaa')}UTC删除您的帐户
(格式是一个日期fns函数,如果需要,可以使用其他lib);
这有点“黑客”,因为这仍然使用本地时区,但如果你只想显示日期而不是时区,那么这就可以了。
Date.prototype.toUTCArray= function(){
var D= this;
return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
D.getUTCMinutes(), D.getUTCSeconds()];
}
Date.prototype.toISO= function(){
var tem, A= this.toUTCArray(), i= 0;
A[1]+= 1;
while(i++<7){
tem= A[i];
if(tem<10) A[i]= '0'+tem;
}
return A.splice(0, 3).join('-')+'T'+A.join(':');
}
这是我的方法:
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
生成的utc对象实际上不是utc日期,而是转换为与utc时间匹配的本地日期(请参见注释)。然而,在实践中,它确实起到了作用。
更新:当调用UTC.toString()、UTC.toLocaleString()等时,这个答案是获取UTC日期的一种快速而肮脏的方法。不过,有更好的解决方案,尤其是现在使用现代浏览器的情况下,我应该改进一下答案。基本上,.toISOString()(IE 9+)是您想要使用的。