Neslihan
Neslihan

Reputation: 33

How to convert long or string to date format (like HH:mm:ss) in javascript?

I have a array of objects as below,

...
{"key_as_string": "14:11:00", //string type
 "key": 1529579460000,    // key_as_string date of type 
 "doc_count": 25
 },
...

How to convert date type HH:mm:ss from key_as_string or key?

Upvotes: 1

Views: 54

Answers (2)

Álvaro Romero
Álvaro Romero

Reputation: 61

You could try this:

var timeFromJSON = JSONName.key_as_string;

var hours = timeFromJSON.split(':')[0];
var minutes = timeFromJSON.split(':')[1];
var seconds = timeFromJSON.split(':')[2];

var date = new Date(0, 0, 0, hours, minutes, seconds);

And now you could do something like this:

date.getHours();   // Expected output: 14
date.getMinutes(); // Expected output: 11
date.getSeconds(); // Expected output: 0

Upvotes: 1

mscdeveloper
mscdeveloper

Reputation: 2889

Maybe like this:

var long_date=1529579460000;
var date = new Date(long_date);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var out_date = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(out_date);

Upvotes: 0

Related Questions