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!!!
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!!!
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);
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));