[Solved-5 Solutions] Convert a Unix timestamp to time in javascript - javascript tutorial
Problem:
How to convert unix timestamp to time in javascript ?
For example, in HH/MM/SS
format.
Solution 1:
You can use this code:
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
Read Also
Timstamp javascriptSolution 2:
Using this timeconverter function to get year, month, date, hour, min, sec.
function timeConverter(UNIX_timestamp){
var a = new Date(UNIX_timestamp * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
return time;
}
Solution 3:
JavaScript works in milliseconds, so we have to convert the UNIX timestamp from seconds to milliseconds.
var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...
Solution 4:
Using Date.format() library, which implements JavaScript date formatting in the style of PHP's date() function.
new Date(unix_timestamp * 1000).format('h:i:s')
Solution 5:
Based on a Unix timestamp:
var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );
Based on a MySQL date string:
var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );