skip to Main Content

I am trying to convert a decimal number to a date object in Javascript. I have tried multiple methods and using moment, but all my conversions are wrong. An example of a value I want to convert is 705623516.402048. I have tried to interpret the int part as seconds and the decimal part as milliseconds, but it has gone wrong too.

I cannot use JQuery, just plain JS or moment

Any help is greatly appreciated

Thanks in advance

2

Answers


  1. If that’s supposed to be today’s date, it looks like it’s seconds since 2001-01-01. So you can use Date.setSeconds() to add to that date.

    let seconds = 705623516.402048;
    let date = new Date('2001-01-01 00:00:00');
    date.setSeconds(date.getSeconds() + seconds);
    console.log(date);
    Login or Signup to reply.
  2. The time value appears to be microseconds. Based on Barmar’s answer, you can maintain millisecond precision (the best ECMAScript Dates can do currently) using:

    let seconds = 705623516.402048;
    let date = new Date(Date.UTC(2001, 0) + seconds * 1e3);
    
    console.log(date);

    Date epochs are typically UTC (though not certainly), hence the use of Date.UTC.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search