将字符串转换为js中的日期 [英] Converting string to date in js

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

问题描述

如何将字符串转换为js中的日期?

How can I convert a string to date in js?

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,并以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格式),您应该将datetime字符串表示形式拆分为部件,然后可以使用datetime部件使用构造函数,例如: 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.

替代方法 - 使用适当的库: / strong>

Alternate method - use an appropriate library:

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

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

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

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