Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

javascript - Date.parse(new Date(...)) NaN in Safari

This is a specific issue with Safari supporting a feature I have, and I'm certain it's my own inability making it moot. See, this returns a number in Chrome and Firefox, but returns NaN in Safari (latest version, 7).

var something = Date.parse(new Date(dataLabels[0]));
console.log(something); // returns epoch number Chrome/Firefox NOT Safari

It seems obtuse to generate a epoch timestamp from a string like that, but that's the only way I could get it to work in my charting project I noticed this in. Am I approaching the translation of mm/dd/yyyy to epoch wrong?

...I'll file a bug report, but wanted to check here for a programmatic error first.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Am I approaching the translation of mm/dd/yyyy to epoch wrong?

Yes. ES5 says:

Unrecognizable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN.

Do not leave parsing of date strings to the Date constructor. Until ES5, parsing of strings was entirely implementation dependent. A version of !SO 8601 was introduced with ES5, however it's not supported by all browsers in use and, depending on the string, may be handled as either UTC or local time by different browsers (including the most recent versions).

The safest way is to manually parse the string.

Given that the format is m/d/y, the following will work reliably in all browsers:

// Return a date object given a dates string in m/d/y format
function parseDate(s) {
  var b = s.split(/D+/);
  return new Date(b[2], --b[0], b[1]);
}

If you are after the actual time value, you can use getTime or just use the unary + operator:

var timeValue = +parseDate('5/24/2014');

Note that when you do:

> Date.parse(new Date(dataLabels[0]))

The date constructor will first parse the string to a date, then convert that to a string, then convert that back to a date, then return the time value. So if the initial parsing failed, the rest will too and if the initial parsing succeeds (and it may or may not depending on the browser) the result will be no different to:

+new Date(dataLabels[0]);

unless the Date constructor is incapable of parsing its own string representation of a Date (which is possible, but not consistent with ECMA-262).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...