假设您网站的用户输入了一个日期范围。
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对象,如何将第一个“本地化”日期范围转换为服务器能够理解的内容?
当前回答
转换为ISO而不更改日期/时间
var now = new Date(); // Fri Feb 20 2015 19:29:31 GMT+0530 (India Standard Time)
var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
//OUTPUT : 2015-02-20T19:29:31.238Z
转换为ISO并更改日期/时间(日期/时间将更改)
isoDate = new Date(now).toISOString();
//OUTPUT : 2015-02-20T13:59:31.238Z
Fiddle链接
其他回答
转换为ISO而不更改日期/时间
var now = new Date(); // Fri Feb 20 2015 19:29:31 GMT+0530 (India Standard Time)
var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
//OUTPUT : 2015-02-20T19:29:31.238Z
转换为ISO并更改日期/时间(日期/时间将更改)
isoDate = new Date(now).toISOString();
//OUTPUT : 2015-02-20T13:59:31.238Z
Fiddle链接
var myDate = new Date(); // Set this to your date in whichever timezone.
var utcDate = myDate.toUTCString();
我刚刚发现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');
另一种转换为UTC并将其保留为日期对象的解决方案:(它的工作方式是从格式化字符串的末尾删除“GMT”部分,然后将其放回Date构造函数中)
var now=新日期();var now_utc=新日期(now.toUTCString().slice(0,-4));控制台日志(now_utc)
我需要这样做来与日期时间选择器库交互。但总的来说,这样处理约会是个坏主意。
用户通常希望使用本地时间的日期时间,因此您可以更新服务器端代码以正确解析带有偏移量的日期时间字符串,然后转换为UTC(最佳选项),或者在发送到服务器之前转换为UTC字符串(如Will Stern的回答)
简单又愚蠢
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());