1

How can I convert this date format (2020-08-18T08:00:00), to milliseconds in javascript?

I'm using momentJS, but I haven't found how to do this conversion.

Thanks!!!

2 Answers2

0

You can create a new Date and use getTime(). Because of absence of timezone it's calculated on the users timezone and not UTC or serverside timezone.

Edited: Because different browser (e.g. Safari and Firefox) produce different results Why does Date.parse give incorrect results? I changed my code so is the date now generated by a secure method by programatical and not automatic parsing of the datestring.

In the old version I had: let date = new Date(dateStr); which works on the most browser but not on all as RobG mentioned.

let dateStr = '2020-08-18T08:00:00';

let parts = dateStr.split('T');
let datParts = parts[0].split('-');
let timeParts = parts[1].split(':');

let date = new Date(datParts[0], datParts[1]-1, datParts[2], timeParts[0], timeParts[1], timeParts[2]);

let ms = date.getTime()
console.log(ms);
Sascha
  • 4,576
  • 3
  • 13
  • 34
  • Should work in theory, doesn't work in practice. E.g. Safari and Firefox produce different results. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Aug 18 '20 at 03:05
  • @RobG - I changed it, so now it should work on all browsers. – Sascha Aug 18 '20 at 03:35
  • Yes, manual parse, consider `let [y, m, d, hr, min, sec] = dateStr.split(/\D/)`. :-) – RobG Aug 18 '20 at 22:13
-1

You can pass that entire string to Date.parse() to get the milliseconds.

A caveat though: As others have pointed out, your date lacks a timezone so you'll be limited to the timezone in which the script is run.

const millis = Date.parse('2020-08-18T08:00:00');
console.log(millis);
console.log(new Date(millis));
JVDL
  • 1,157
  • 9
  • 16
  • And parsing is inconsistent, Safari returns a different result to other browsers. – RobG Aug 18 '20 at 03:06
  • Yeah sure, because the time passed isn't accurate, so Safari will give the local time vs other implementations that provide UTC. – JVDL Aug 19 '20 at 06:59
  • That format is supposed to be parsed as local but Safari parses it as UTC. – RobG Aug 19 '20 at 08:36