-2

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

Dexygen
  • 12,287
  • 13
  • 80
  • 147
Rodolfo Conde
  • 49
  • 1
  • 7

2 Answers2

2

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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.

RobG
  • 142,382
  • 31
  • 172
  • 209