skip to Main Content

I am trying to convert a UNIX timestamp to a human-readable date in JavaScript, but I am getting unexpected results. The UNIX timestamp I have is 665346600, which should correspond to February 1, 2022.

I am using the following JavaScript code to perform the conversion:

const timestampInSeconds = 665346600;
const timestampInMilliseconds = timestampInSeconds * 1000;

const date = new Date(timestampInMilliseconds);

console.log(date.toISOString());

However, the output I am getting is 1991-03-02T17:16:40.000Z, which is incorrect. I was expecting 2022-02-01T05:30:00.000Z.

I have double-checked the timestamp value and also tried various online timestamp conversion tools, all of which confirm that 665346600 corresponds to February 1, 2022.

Am I doing something wrong in my code, or is there a different approach I should be using to correctly convert this UNIX timestamp to the corresponding date?

Any help in resolving this issue would be greatly appreciated. Thank you!

2

Answers


  1. Your code is correct and should work as expected for converting a UNIX timestamp to a JavaScript Date object. UNIX timestamp you have provided (665346600) actually corresponds to the date "1991-03-02 17:16:40 UTC" and not "2022-02-01 05:30:00 UTC".

    UNIX timestamp is the number of seconds that have elapsed since the Unix epoch that is the time 00:00:00 UTC on Thursday, 1 January 1970, minus leap seconds.

    UNIX timestamp of 665346600 seconds would correspond to approximately 21 years after the start of the Unix epoch which would put it in the year 1991. This matches the date that you are getting in your output.

    If you confident that your UNIX timestamp should correspond to February 1, 2022 then there might be a mistake in your UNIX timestamp.

    For FYI, the correct UNIX timestamp for "2022-02-01 05:30:00 UTC" should be 1643706600.You can convert this timestamp to a JavaScript Date as below,

    const timestampInSeconds = 1643706600;
    const timestampInMilliseconds = timestampInSeconds * 1000;
    
    const date = new Date(timestampInMilliseconds);
    
    console.log(date.toISOString());
    
    Login or Signup to reply.
  2. When you create a date object from a timestamp it’s created in UTC.

    To fix that you should shift minutes with the timezone offset:

    const timestampInSeconds = 665346600;
    const timestampInMilliseconds = timestampInSeconds * 1000;
    
    const date = new Date(timestampInMilliseconds);
    
    // fix the timezone offset
    date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    
    console.log(date.toISOString());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search