0

Im building a timeclock app with Angular 5. In this app I calculate the total hours using this method.

Chrome:

const start = +new Date(2018-07-24 + ' ' + 14:00);
const elapsed = +new Date(2018-07-24 + ' ' + 14:45) - start;
this.clockedInHours = elapsed / 3600000;

resulting in the total hours clocked in being 0.75

Running the same code in safari returns NaN

I found using the letter 'T' instead of the space when setting the date/time returns number values in safari

const start = +new Date(2018-07-24 + 'T' + 14:00);
const elapsed = +new Date(2018-07-24 + 'T' + 14:45) - start;
this.clockedInHours = elapsed / 3600000;

but instead of getting 0.75 for the total, im getting

4763748.75 in safari

and

4763754.75 in chrome

bjwhip
  • 407
  • 1
  • 9
  • 18
  • Parsing dates in JS is entirely browser dependent. If possible pass the seconds since 01 January, 1970 UTC, which is the default/min date in JavaScript – Adam H Jul 24 '18 at 21:45
  • you need to parse an official date format if you want cross-browser handling. any one of the output flavors will be portable. – dandavis Jul 24 '18 at 22:57
  • @AdamH—not entirely. There is a format specified in ECMA-262 that is (nearly) ISO 8601, and ECMAScript 2019 will specify 2 more formats. But yes, the built–in parser should be avoided. – RobG Jul 25 '18 at 02:42
  • Without the "T" it's not consistent with ECMA-262 so browsers fall back to implementation specific heuristics. Safari is entitled to return an invalid date as the format is *nearly* correct but not entirely. With the "T", it should be treated as local but Safari incorrectly treats it as UTC. That's a straight bug. The usual answer is *don't use the built–in parser*, use a library or write your own, it's not hard for a single format (3 or 4 lines of code). – RobG Jul 25 '18 at 02:46

0 Answers0