在 JavaScript 中将字符串解析为日期 [英] Parsing a string to a date in JavaScript

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

问题描述

如何在 JavaScript 中将字符串转换为 Date 对象?

How can I convert a string to a Date object 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-DDYYYY-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 - 例如:new Date('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 兼容性(小于 9 的 IE 版本不支持 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天全站免登陆