javascript 如何在javascript中将字符串转换为Date类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9503128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a string to Date class in javascript?
提问by The Light
var from = "2012-01-13 T11:00:00";
Date date = parseDate(from);
How can I convert this text to a Date object?
如何将此文本转换为 Date 对象?
回答by ruphus
According to thisarticle, you can use different date patterns:
根据这篇文章,您可以使用不同的日期模式:
MM/dd/yyyy
yyyy/MM/dd
MM-dd-yyyy
MMMM dd, yyyy
MMM dd, yyyy
and date-time patterns:
和日期时间模式:
MM/dd/yyyy hh:mm:ss tt
MMMM dd, yyyy HH:mm:ss
In your case the simplest thing to do (maybe) is to remove the T
character and replace -
separators with /
:
在您的情况下,最简单的方法(可能)是删除T
字符并将-
分隔符替换为/
:
function parseDate(from){
from = from.replace('T', '').replace(/-/g,'/');
return new Date(from);
}
回答by ninjagecko
You can parse your string manually and then use the constructors in https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
您可以手动解析您的字符串,然后使用https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date 中的构造函数
However, see javascript - string to date - php iso string format
但是,请参阅javascript - 迄今为止的字符串 - php iso 字符串格式
According to the ECMAScript 5 specification (p171):
根据 ECMAScript 5 规范 (p171):
15.9.3.2 new Date (value)
[...]
If Type(v) is String, then [...] Parse v as a date, in exactly
the same manner as for the parse method (15.9.4.2); let V be the
time value for this date.
And according to https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parsethe functions accepts only RFC2822or ISO 8601date formats. This means that you are allowed to do new Date(YOUR_FORMAT_STRING)
but it is only valid if your dates are that format.
并且根据https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse函数只接受RFC2822或ISO 8601日期格式。这意味着您可以这样做,new Date(YOUR_FORMAT_STRING)
但仅当您的日期是该格式时才有效。
回答by It Grunt
Please refer to the JavaScript Date Reference. From there you can split/parse the date and construct a DATE object.
请参阅JavaScript 日期参考。从那里您可以拆分/解析日期并构造一个 DATE 对象。