在JavaScript中将字符串转换为日期 [英] Converting a string to a date in JavaScript

查看:189
本文介绍了在JavaScript中将字符串转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在JavaScript中将字符串转换为日期?

How can I convert a string to a date in JavaScript?

var st = "date in some format"
var dt = new date();

var dt_st= //st in date format same as dt


推荐答案

字符串解析的最佳字符串格式是日期ISO格式以及JavaScript Date对象构造函数。

The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.

ISO格式示例: YYYY-MM-DD YYYY-MM-DDTHH :MM:SS

Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

但等等!仅使用ISO格式无法可靠地运行本身。字符串有时被解析为UTC,有时也被解析为本地时间(基于浏览器供应商和版本)。最佳做法应始终是将日期存储为UTC并进行UTC计算。

But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.

要将日期解析为UTC,请附加 Z - 例如:新日期('2011-04-11T10:20:30Z')

To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').

显示日期在UTC中,使用 .toUTCString()

以用户当地时间显示日期,使用 .toString()

To display a date in UTC, use .toUTCString(),
to display a date in user's local time, use .toString().

关于 MDN |日期此答案

Internet Explorer兼容性(IE版本小于9不支持Date构造函数中的ISO格式),您应该将日期时间字符串表示形式分割为它的部分,然后您可以使用构造函数使用日期时间部分,例如: new Date(' 2011','04' - 1,'11','11','51','00')。请注意,月份数必须少1个。

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.

备用方法 - 使用适当的库:

您还可以利用图书馆 Moment.js 允许使用指定的时区解析日期。

You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.

这篇关于在JavaScript中将字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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