[英]Converting String date to Date object
I have a variable which is retrieved from php, and is stored in a variable called activity.ActivityDate
. 我有一个从php检索到的变量,并存储在一个名为
activity.ActivityDate
的变量中。 When I do a 当我做一个
console.log(activity.ActivityDate);
It outputs 14/06/2016
, which is a valid format which can be turned into a date object. 它输出
14/06/2016
,这是可以转换为日期对象的有效格式。 But when I do 但是当我这样做
d = new Date(activity.ActivityDate);
console.log(d);
I get an invalid date. 我得到一个无效的日期。 But when I do
但是当我这样做
e = new Date('14/06/2016');
console.log(e);
I do get a proper date object. 我确实得到了正确的日期对象。
Is there something wrong with my activity.ActivityDate
string, or some way to turn it into a proper string? 我的
activity.ActivityDate
字符串是否有问题,或将其转换为正确的字符串的某种方法?
Different browsers can parse datestrings differently as noted by MDN it's discouraged to use the Date()
constructor to parse a datestring. 正如MDN所指出的那样,不同的浏览器可以不同地解析日期字符串,因此不建议使用
Date()
构造函数来解析Date()
字符串。 In your case you're giving the format DD/MM/YYYY
, but it's likely your browser is expecting MM/DD/YYYY
. 在您的情况下,您给出的格式为
DD/MM/YYYY
,但是您的浏览器可能期望使用MM/DD/YYYY
。
Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.
注意:由于浏览器的差异和不一致,强烈建议不要使用Date构造函数(和Date.parse,它们等效)来解析日期字符串。
The best thing to do so it would work in all browsers would be to spilt your string by "/"
and convert your numbers into integers then use the constructor format for the Date(year, month, day)
constructor. 为此,最好的做法是在所有浏览器中都起作用,将字符串用
"/"
溢出,然后将数字转换为整数,然后对Date(year, month, day)
构造函数使用构造函数格式。
For example: 例如:
var date = '14/06/2016'; var items = date.split('/'); var day = +items[0]; // Note +(item) means convert to interger var month= +(items[1] - 1); // month goes from 0-11 rather than 1-12. var year = +items[2]; e = new Date(year, month, day); console.log(e);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.