0

I am new to javascript and have the following string '2023-06-19 05:00:00.554' and want to convert it to epoch i am trying something like this

var s = "2023-06-19 05:00:00.554";
var epoch = new Date(s).getTime();

console.log(epoch);

but it give wrong results any idea how to achieve this ?

pilchard
  • 12,414
  • 5
  • 11
  • 23
jsor
  • 97
  • 5

2 Answers2

0

As explained by Ricky Mo you must specify the timezone value of your date,
otherwise the system will use the host system's timezone at this date (with STD or DST calculation).

2 ways

var s = "2023-06-19T05:00:00.554+00:00"
// or
var s = "2023-06-19T05:00:00.554Z" //  Zulu time zone

thanks to Darryl Noakes for reminding me Z (stand for "Zulu" from the ICAO) (but I remember more easily the notation with the positive + or negative - sign with the value of the time difference in ±hh:mm)

var s = "2023-06-19T05:00:00.554+00:00";  // GMT 0 -> + 0h, 0mn
var epoch = new Date(s).getTime();

console.log(epoch); //  1687150800554 everywhere in the world!
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • You can also use the `Z` suffix instead of `+00:00` if you use ISO timestamps. Not sure about non-ISO ones. – Darryl Noakes Jun 20 '23 at 01:15
  • @DarrylNoakes see https://stackoverflow.com/questions/14714548/does-utc-date-string-require-the-format-specifier-z-even-if-that-string-includ/14714611#14714611 – Mister Jojo Jun 20 '23 at 01:39
0

Assuming you have string "2023-06-19 05:00:00.554" and it represents GMT, you need to first convert that to a ISO 8601 format string, so that it can be converted to a Date object reliably, regardless of the browser used. The ISO format of your input is "2023-06-19T05:00:00.554Z"

Code using a regex to convert your input to the ISO format:

const s = "2023-06-19 05:00:00.554";
let epoch = new Date(s.replace(/ (.*)$/, 'T$1Z')).getTime();
console.log(epoch); // output: 1687150800554
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20