Question

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.

Was it helpful?

Solution

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).

OTHER TIPS

Date.parse(new Date(dataLabels[0]).toString()) should work across browsers. In a less obtuse way, new Date(dataLabels[0]).valueOf() should also have the same effect. valueOf() is the toString() equivalent that returns a number, and it's well-supported too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top