skip to Main Content

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 ?

2

Answers


  1. 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!
    Login or Signup to reply.
  2. 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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search