如何将 JavaScript 日期转换为 UTC? [英] How do you convert a JavaScript date to UTC?

查看:24
本文介绍了如何将 JavaScript 日期转换为 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 日期对象,您如何将第一个本地化"日期范围转换为服务器可以理解的内容?

Using the JavaScript Date object, how would you convert the first "localized" date range into something the server will understand?

推荐答案

toISOString() 方法返回简化扩展 ISO 中的字符串格式(ISO 8601),长度始终为 24 或 27 个字符(YYYY-MM-DDTHH:mm:ss.sssZ±YYYYYY-MM-DDTHH:mm:ss.sssZ,分别).时区始终为零 UTC 偏移量,如后缀Z".

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".

来源:MDN 网络文档

您需要的格式是使用 .toISOString() 方法创建的.对于本机不支持此方法的旧浏览器(ie8 及以下),可以找到 shim 此处:

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 isoDateString = new Date().toISOString();
console.log(isoDateString);

对于时区工作,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆