Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert milliseconds to date and time?

I know this question has been asked and answered many times, but I could not convert a given milliseconds to date and time.

I have the following code:

var date = '1475235770601';
var d = new Date(date);
var ds = d.toLocaleString();
alert(ds);
console.log(ds);

When I run this I see Invalid Date in console as well as in alert.

But when I paste the milliseconds here, it converts fine in the format in local date and time as Fri Sep 30 2016 17:12:50.

Actually I want to convert in in the format 09/30/16 17:12:50.

like image 639
Nongthonbam Tonthoi Avatar asked Oct 05 '16 20:10

Nongthonbam Tonthoi


2 Answers

Date's constructor takes a number, not a string. Either feed it in directly:

date = 1475235770601; // Note the lack of quotes making it a number

Or, if you already have a string, convert it explicitly:

date = parseInt(date);
like image 177
Mureinik Avatar answered Oct 13 '22 00:10

Mureinik


I ended up changing my code like this:

var date = '1475235770601';
var d = new Date(parseInt(date, 10));
var ds = d.toString('MM/dd/yy HH:mm:ss');
console.log(ds);

Output:

09/30/16 17:12:50
like image 22
Nongthonbam Tonthoi Avatar answered Oct 13 '22 01:10

Nongthonbam Tonthoi