[javascript] Convert a Unix timestamp to time in JavaScript

I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?

For example, in HH/MM/SS format.

This question is related to javascript date time time-format

The answer is


Pay attention to the zero problem with some of the answers. For example, the timestamp 1439329773 would be mistakenly converted to 12/08/2015 0:49.

I would suggest on using the following to overcome this issue:

var timestamp = 1439329773; // replace your timestamp
var date = new Date(timestamp * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
console.log(formattedDate);

Now results in:

12/08/2015 00:49

If you want to convert Unix time duration to real hours, minutes, and seconds, you could use the following code:

var hours = Math.floor(timestamp / 60 / 60);
var minutes = Math.floor((timestamp - hours * 60 * 60) / 60);
var seconds = Math.floor(timestamp - hours * 60 * 60 - minutes * 60 );
var duration = hours + ':' + minutes + ':' + seconds;

I'm partial to Jacob Wright's 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')

Shortest

(new Date(ts*1000)+'').slice(16,24)

_x000D_
_x000D_
let ts = 1549312452;
let time = (new Date(ts*1000)+'').slice(16,24);

console.log(time);
_x000D_
_x000D_
_x000D_


I'd think about using a library like momentjs.com, that makes this really simple:

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") );

See Date/Epoch Converter.

You need to ParseInt, otherwise it wouldn't work:


if (!window.a)
    window.a = new Date();

var mEpoch = parseInt(UNIX_timestamp);

if (mEpoch < 10000000000)
    mEpoch *= 1000;

------
a.setTime(mEpoch);
var year = a.getFullYear();
...
return time;

Use:

var s = new Date(1504095567183).toLocaleDateString("en-US")
console.log(s)
// expected output "8/30/2017"  

and for time:

_x000D_
_x000D_
var s = new Date(1504095567183).toLocaleTimeString("en-US")
console.log(s)
// expected output "3:19:27 PM"
_x000D_
_x000D_
_x000D_

see Date.prototype.toLocaleDateString()


Another way - from an ISO 8601 date.

_x000D_
_x000D_
var timestamp = 1293683278;_x000D_
var date = new Date(timestamp * 1000);_x000D_
var iso = date.toISOString().match(/(\d{2}:\d{2}:\d{2})/)_x000D_
alert(iso[1]);
_x000D_
_x000D_
_x000D_


JavaScript works in milliseconds, so you'll first have to convert the UNIX timestamp from seconds to milliseconds.

var date = new Date(UNIX_Timestamp * 1000);
// Manipulate JavaScript Date object here...

Code below also provides 3-digit millisecs, ideal for console log prefixes:

_x000D_
_x000D_
const timeStrGet = date => {_x000D_
    const milliSecsStr = date.getMilliseconds().toString().padStart(3, '0') ;_x000D_
    return `${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;_x000D_
};_x000D_
_x000D_
setInterval(() => console.log(timeStrGet(new Date())), 299);
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
function timeConverter(UNIX_timestamp){_x000D_
  var a = new Date(UNIX_timestamp * 1000);_x000D_
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];_x000D_
  var year = a.getFullYear();_x000D_
  var month = months[a.getMonth()];_x000D_
  var date = a.getDate();_x000D_
  var hour = a.getHours();_x000D_
  var min = a.getMinutes();_x000D_
  var sec = a.getSeconds();_x000D_
  var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;_x000D_
  return time;_x000D_
}_x000D_
console.log(timeConverter(0));
_x000D_
_x000D_
_x000D_


// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
   if(value < 10) {
    return '0' + value;
   }
   return value;
}

var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours()) 
      + ':' + twoDigits(date.getMinutes()) 
      + ':' + twoDigits(date.getSeconds());

function getTIMESTAMP() {
  var date = new Date();
  var year = date.getFullYear();
  var month = ("0" + (date.getMonth() + 1)).substr(-2);
  var day = ("0" + date.getDate()).substr(-2);
  var hour = ("0" + date.getHours()).substr(-2);
  var minutes = ("0" + date.getMinutes()).substr(-2);
  var seconds = ("0" + date.getSeconds()).substr(-2);

  return year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
}

//2016-01-14 02:40:01

The problem with the aforementioned solutions is, that if hour, minute or second, has only one digit (i.e. 0-9), the time would be wrong, e.g. it could be 2:3:9, but it should rather be 02:03:09.

According to this page it seems to be a better solution to use Date's "toLocaleTimeString" method.


UNIX timestamp is number of seconds since 00:00:00 UTC on January 1, 1970 (according to Wikipedia).

Argument of Date object in Javascript is number of miliseconds since 00:00:00 UTC on January 1, 1970 (according to W3Schools Javascript documentation).

See code below for example:

    function tm(unix_tm) {
        var dt = new Date(unix_tm*1000);
        document.writeln(dt.getHours() + '/' + dt.getMinutes() + '/' + dt.getSeconds() + ' -- ' + dt + '<br>');

    }

tm(60);
tm(86400);

gives:

1/1/0 -- Thu Jan 01 1970 01:01:00 GMT+0100 (Central European Standard Time)
1/0/0 -- Fri Jan 02 1970 01:00:00 GMT+0100 (Central European Standard Time)

Based on @shomrat's answer, here is a snippet that automatically writes datetime like this (a bit similar to StackOverflow's date for answers: answered Nov 6 '16 at 11:51):

today, 11:23

or

yersterday, 11:23

or (if different but same year than today)

6 Nov, 11:23

or (if another year than today)

6 Nov 2016, 11:23

function timeConverter(t) {     
    var a = new Date(t * 1000);
    var today = new Date();
    var yesterday = new Date(Date.now() - 86400000);
    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();
    if (a.setHours(0,0,0,0) == today.setHours(0,0,0,0))
        return 'today, ' + hour + ':' + min;
    else if (a.setHours(0,0,0,0) == yesterday.setHours(0,0,0,0))
        return 'yesterday, ' + hour + ':' + min;
    else if (year == today.getFullYear())
        return date + ' ' + month + ', ' + hour + ':' + min;
    else
        return date + ' ' + month + ' ' + year + ', ' + hour + ':' + min;
}

You can use the following function to convert your timestamp to HH:MM:SS format :

var convertTime = function(timestamp, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    var date = timestamp ? new Date(timestamp * 1000) : new Date();
    return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

Without passing a separator, it uses : as the (default) separator :

time = convertTime(1061351153); // --> OUTPUT = 05:45:53

If you want to use / as a separator, just pass it as the second parameter:

time = convertTime(920535115, '/'); // --> OUTPUT = 09/11/55

Demo

_x000D_
_x000D_
var convertTime = function(timestamp, separator) {
    var pad = function(input) {return input < 10 ? "0" + input : input;};
    var date = timestamp ? new Date(timestamp * 1000) : new Date();
    return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
    ].join(typeof separator !== 'undefined' ?  separator : ':' );
}

document.body.innerHTML = '<pre>' + JSON.stringify({
    920535115 : convertTime(920535115, '/'),
    1061351153 : convertTime(1061351153, ':'),
    1435651350 : convertTime(1435651350, '-'),
    1487938926 : convertTime(1487938926),
    1555135551 : convertTime(1555135551, '.')
}, null, '\t') +  '</pre>';
_x000D_
_x000D_
_x000D_

See also this Fiddle.


The modern solution that doesn't need a 40 KB library:

Intl.DateTimeFormat is the non-culturally imperialistic way to format a date/time.

// Setup once
var options = {
    //weekday: 'long',
    //month: 'short',
    //year: 'numeric',
    //day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
},
intlDate = new Intl.DateTimeFormat( undefined, options );

// Reusable formatter
var timeStamp = 1412743273;
console.log( intlDate.format( new Date( 1000 * timeStamp ) ) );

function timeConverter(UNIX_timestamp){
 var a = new Date(UNIX_timestamp*1000);
     var hour = a.getUTCHours();
     var min = a.getUTCMinutes();
     var sec = a.getUTCSeconds();
     var time = hour+':'+min+':'+sec ;
     return time;
 }

shortest one-liner solution to format seconds as hh:mm:ss: variant:

_x000D_
_x000D_
console.log(new Date(1549312452 * 1000).toISOString().slice(0, 19).replace('T', ' '));_x000D_
// "2019-02-04 20:34:12"
_x000D_
_x000D_
_x000D_


In moment you must use unix timestamp:

const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");

This works with PHP timestamps

_x000D_
_x000D_
var d = 1541415288860;
//var d =val.timestamp;

//NB: use + before variable name
var date = new Date(+d);

console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());
_x000D_
_x000D_
_x000D_

var d =val.timestamp;
var date=new Date(+d); //NB: use + before variable name

console.log(d);
console.log(date.toDateString());
console.log(date.getFullYear());
console.log(date.getMinutes());
console.log(date.getSeconds());
console.log(date.getHours());
console.log(date.toLocaleTimeString());

the methods above will generate this results

1541415288860
Mon Nov 05 2018 
2018 
54 
48 
13
1:54:48 PM

There's a bunch of methods that work perfectly with timestamps. Cant list them all


Using Moment.js, you can get time and date like this:

var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");

And you can get only time using this:

var timeString = moment(1439198499).format("HH:mm:ss");

The answer given by @Aron works, but it didn't work for me as I was trying to convert timestamp starting from 1980. So I made few changes as follows

_x000D_
_x000D_
function ConvertUnixTimeToDateForLeap(UNIX_Timestamp) {_x000D_
    var dateObj = new Date(1980, 0, 1, 0, 0, 0, 0);_x000D_
    dateObj.setSeconds(dateObj.getSeconds() + UNIX_Timestamp);_x000D_
    return dateObj;  _x000D_
}_x000D_
_x000D_
document.body.innerHTML = 'TimeStamp : ' + ConvertUnixTimeToDateForLeap(1269700200);
_x000D_
_x000D_
_x000D_

So if you have a timestamp starting from another decade or so, just use this. It saved a lot of headache for me.


moment.js

convert timestamps to date string in js

https://momentjs.com/

moment().format('YYYY-MM-DD hh:mm:ss');
// "2020-01-10 11:55:43"

moment(1578478211000).format('YYYY-MM-DD hh:mm:ss');
// "2020-01-08 06:10:11"



Modern Solution (for 2020)

In the new world, we should be moving towards the standard Intl JavaScript object, that has a handy DateTimeFormat constructor with .format() method:

_x000D_
_x000D_
function format_time(s) {
  const dtFormat = new Intl.DateTimeFormat('en-GB', {
    timeStyle: 'medium',
    timeZone: 'UTC'
  });
  
  return dtFormat.format(new Date(s * 1e3));
}

console.log( format_time(12345) );  // "03:25:45"
_x000D_
_x000D_
_x000D_


Eternal Solution

But to be 100% compatible with all legacy JavaScript engines, here is the shortest one-liner solution to format seconds as hh:mm:ss:

_x000D_
_x000D_
function format_time(s) {
  return new Date(s * 1e3).toISOString().slice(-13, -5);
}

console.log( format_time(12345) );  // "03:25:45"
_x000D_
_x000D_
_x000D_

Method Date.prototype.toISOString() returns time in simplified extended ISO 8601 format, which is always 24 or 27 characters long (i.e. YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ respectively). The timezone is always zero UTC offset.

This solution does not require any third-party libraries and is supported in all browsers and JavaScript engines.


_x000D_
_x000D_
function getDateTimeFromTimestamp(unixTimeStamp) {
    let date = new Date(unixTimeStamp);
    return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
}

const myTime = getDateTimeFromTimestamp(1435986900000);
console.log(myTime); // output 01/05/2000 11:00
_x000D_
_x000D_
_x000D_


function getDateTime(unixTimeStamp) {

    var d = new Date(unixTimeStamp);
    var h = (d.getHours().toString().length == 1) ? ('0' + d.getHours()) : d.getHours();
    var m = (d.getMinutes().toString().length == 1) ? ('0' + d.getMinutes()) : d.getMinutes();
    var s = (d.getSeconds().toString().length == 1) ? ('0' + d.getSeconds()) : d.getSeconds();

    var time = h + '/' + m + '/' + s;

    return time;
}

var myTime = getDateTime(1435986900000);
console.log(myTime); // output 01/15/00

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to time-format

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone How to convert milliseconds to "hh:mm:ss" format? JavaScript seconds to time string with format hh:mm:ss How do I convert datetime to ISO 8601 in PHP Javascript add leading zeroes to date Get month name from Date Getting Hour and Minute in PHP Convert seconds to HH-MM-SS with JavaScript? How to display a date as iso 8601 format with PHP Convert a Unix timestamp to time in JavaScript