3

How to convert 1304921325178.3193 to yyyy-mm-dd -> in javascript?

I use highchart and I would like to convert data(xAxis[0]0) to yyyy-mm-dd.

I tried to parse the millisecond using this function

function(valTime) {
 var date = new Date(valTime);
 var y = date.getFullYear();
 var m = date.getMonth() + 1;    
 var d = date.getDate();    
 m = (m < 10) ? '0' + m : m; 
 d = (d < 10) ? '0' + d : d;
 return [y, m, d].join('-');
}

However, there is a gap between actual date(2015-01-26) and selected date in the chart (2015-01-29). captured image I guess if I calculate .3193, the date will be matched.

Is there any way to get the right date from the millisecond?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Gil
  • 105
  • 2
  • 5
  • 12
  • 1
    Possible duplicate of [Converting milliseconds to a date (jQuery/JS)](https://stackoverflow.com/questions/4673527/converting-milliseconds-to-a-date-jquery-js) – sliptype Mar 06 '18 at 16:17
  • 1
    You can convert millisecond to date by `new Date(millisecond)`. But this is `Date`. You might want to see https://momentjs.com to display the Date in your preferred format. – ntalbs Mar 07 '18 at 12:04

1 Answers1

5

Your ms are actually pointing to 2011-05-09T06:08:45.178Z:

var date = new Date(1304921325178.3193); // Date 2011-05-09T06:08:45.178Z
var year = date.getFullYear();
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + date.getDate()).slice(-2);
    
console.log(`${year}-${month}-${day}`); // 2011-05-09
guijob
  • 4,413
  • 3
  • 20
  • 39