如何将JavaScript日期转换为UTC? [英] How do you convert a JavaScript date to UTC?
问题描述
假设您的网站的用户输入日期范围。
Suppose a user of your website enters a date range.
2009-1-1 to 2009-1-3
您需要将此日期发送到服务器进行某些处理,但服务器期望所有日期和时间在UTC。
You need to send this date to a server for some processing, but the server expects all dates and times to be in UTC.
现在假设用户在阿拉斯加或夏威夷或斐济。由于它们在时区与UTC完全不同,所以日期范围需要转换成如下所示:
Now suppose the user is in Alaska or Hawaii or Fiji. Since they are in a timezone quite different from UTC, the date range needs to be converted to something like this:
2009-1-1T8:00:00 to 2009-1-4T7:59:59
使用JavaScript Date对象您将如何将第一个本地化的日期范围转换成服务器将理解的内容?
Using the JavaScript Date object, how would you convert the first "localized" date range into something the server will understand?
推荐答案
创建所需的格式使用 .toISOString()
方法。对于本来不支持此方法的旧浏览器(即8及更低版本),可以找到垫片这里:
The format you need is created with the .toISOString()
method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found here:
这将使您有能力完成所需:
This will give you the ability to do what you need:
var isoDate = new Date('yourdatehere').toISOString();
对于时区工作, moment.js和moment.js时区是非常宝贵的工具,特别是在客户端和服务器之间导航时区javascript。
For Timezone work, moment.js and moment.js timezone are really invaluable tools...especially for navigating timezones between client and server javascript.
这篇关于如何将JavaScript日期转换为UTC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!