简体   繁体   English

简单的方法来将格式化为日期的字符串转换为Javascript中的Date对象?

[英]Easy way to convert a string that is formatted as a date into a Date object in Javascript?

I have a date string that looks like this: 2014-07-21T12:55:31.513Z . 我有一个看起来像这样的日期字符串: 2014-07-21T12:55:31.513Z Is there some simple way to convert this to a date? 有一些简单的方法可以将此转换为日期吗? I found that there is Date.parse() however that dives me milliseconds since Jan. 1st, 1970 which it doesn't look like that fits my needs. 我发现有Date.parse(),但是它从1970年1月1日开始潜入毫秒,这看起来不符合我的需求。

new Date("2014-07-21T12:55:31.513Z")

您还应该在这里看看: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

use 采用

new Date('2014-07-21T12:55:31.513Z')

the ISO format : ISO格式

 YYYY-MM-DD

or 要么

YYYY-MM-DDTHH:MM:SS

refer Date 参考日期

Note : Where Date is called as a constructor with more than one argument, if values are greater than their logical range (eg 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. 注意 :如果将Date用作具有多个参数的构造函数,则如果值大于其逻辑范围(例如,将13作为月份值或70作为分钟值),则会调整相邻的值。 Eg new Date(2013,13,1) is equivalent to new Date(2014,1,1), both create a date for 2014-02-01 (note that the month is 0-based). 例如,新的Date(2013,13,1)等同于新的Date(2014,1,1),两者都为2014-02-01创建一个日期(请注意,该月是从0开始的)。 Similarly for other values: new Date(2013,2,1,0,70) is equivalent to new Date(2013,2,1,1,10) which both create a date for 2013-03-01T01:10:00. 同样,对于其他值:new Date(2013,2,1,0,70)等同于new Date(2013,2,1,1,10),两者都会为2013-03-01T01:10:00创建一个日期。

不知道这是否是最好的方法,但是我只是使用以下功能解析字符串以隔离年,月,日,小时,分钟,秒和毫秒:

var date = new Date(year, month, day, hours, minutes, seconds, milliseconds);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM