问题
How to convert the string which is having date time to date time format. My code is:
In Chrome its working fine:
var str = "05-Sep-2013 01:05:15 PM "
var res = Date.parse(str)
console.log(res) //o/p:1378366515000
var result = new Date(res)
console.log(result) //o/p:Thu Sep 05 2013 13:05:15 GMT+0530 (India Standard Time)
In Firefox and IE:
console.log(res) //o/p: NaN
console.log(result) //o/p: Date {Invalid Date}
Could you please help me out. thanks in advance.
回答1:
Parse the string yourself as suggested on
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).
I gave you a link to an answer on SO that explains how to do this.
Converting String into date format in JS
This example should work even on very old or very broken browsers.
var lookupMonthName = {
jan: 0,
feb: 1,
mar: 2,
apr: 3,
may: 4,
jun: 5,
jul: 6,
aug: 7,
sep: 8,
oct: 9,
nov: 10,
dec: 11
};
function customParse(dateTimeStr) {
var dateTime = dateTimeStr.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '').split(' ');
var date = dateTime[0].split('-');
date[1] = lookupMonthName[date[1].toLowerCase()].toString();
date.reverse();
var time = dateTime[1].split(':');
if (dateTime[2].toUpperCase() === 'PM') {
time[0] = (parseInt(time[0], 10) + 12).toString();
}
var args = date.concat(time);
console.log(args);
return new Date(Date.UTC.apply(null, args));
}
var str = '05-Sep-2013 01:05:15 PM ';
var date = customParse(str);
document.getElementById('out').appendChild(document.createTextNode(date));
console.log(date);
<pre id="out"></pre>
To format a string from a Date object, see SO answers
Where can I find documentation on formatting a date in JavaScript?
A little effort on your part and you would have been able to find this information yourself.
回答2:
IE and FF would like '/' instead of '-' in dates
http://plnkr.co/edit/9ZoHwjvgMA2twEoTJTn9?p=preview
var str = "05-Sep-2013 01:05:15 PM ";
console.log( Date.parse( str ) ); // NaN
console.log( Date.parse( str.replace(/-/g, '/') ) ); // 1378404315000
So parsing gets you the milliseconds, now you can just put it in a date:
var d = new Date( Date.parse( str.replace(/-/g, '/') ) );
console.log( d ); // 2013-09-05T18:05:15.000Z
And there it is, same as your input date but in diff format.
来源:https://stackoverflow.com/questions/39147558/date-parse-is-not-working-in-fire-fox-and-ie-its-working-fine-in-chrome