By roflwaffle


2009-05-11 08:23:28 8 Comments

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.

23 comments

@shomrat 2011-05-21 00:44:36

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;
}
console.log(timeConverter(0));

@shomrat 2011-05-21 00:52:15

for HH/MM/SS just use last three variables and this is time will be in your local time but if you want to get the UTC time just use the getUTC methods. Here's the code.

@user1985189 2014-08-08 16:40:42

I used this solution but tweaked it so that minutes and seconds would show up as :03 or :09 instead of :3 or :9, like so: var min = a.getMinutes() < 10 ? '0' + a.getMinutes() : a.getMinutes(); var sec = a.getSeconds() < 10 ? '0' + a.getSeconds() : a.getSeconds();

@jcampbell1 2014-08-27 17:41:55

Bug: getMonth() returns a month number between 0 and 11, thus a.getMonth() - 1 is wrong.

@Basj 2016-11-06 11:51:22

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;
}

@Dan Alboteanu 2018-05-09 14:04:45

Use:

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

and for time:

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

see Date.prototype.toLocaleDateString()

@Wolfgang 2018-05-09 15:50:43

This is a command to get the date (M/D/YYYY), not the time (HH/MM/SS) as requested.

@Ashish Gupta 2017-07-04 06:59:09

 function getDateTimeFromTimestamp(unixTimeStamp) {
    var 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);
  }

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

@John Slegers 2017-02-24 12:33:36

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

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>';

See also this Fiddle.

@VisioN 2016-03-09 11:37:06

Here is the shortest one-liner solution to format seconds as hh:mm:ss:

/**
 * Convert seconds to time string (hh:mm:ss).
 *
 * @param Number s
 *
 * @return String
 */
function time(s) {
    return new Date(s * 1e3).toISOString().slice(-13, -5);
}

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

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.

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

@Steve Chamaillard 2017-02-09 15:40:49

console.log(time(120)); shows "01:02:00"

@Steve Chamaillard 2017-02-10 08:50:52

I'm pasting your function in Chrome's console :/ Even in your fiddle it's showing 01:02:00 for me ! Tried on Firefox, same results. Very strange...I'm pretty sure it's because I'm GMT+1 !

@Steve Chamaillard 2017-02-10 09:02:40

I've offered an edit for your answer that ignores any timezone, so it'll always show the right formatted value !

@VisioN 2017-02-10 14:28:15

@SteveChamaillard Thank you, Steve. You were right, toTimeString was not working well with time zones. Unfortunately your edit was rejected before I saw it. However, I'd suggest to use toISOString instead, since toGMTString is deprecated and may return different results on different platforms.

@SamGoody 2018-05-22 09:33:17

Even shorter with ES6: let time = s => new Date(s * 1e3).toISOString().slice(-13, -5)

@Valix85 2016-06-24 09:26:30

In moment you must use unix timestamp:

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

@ArBro 2016-06-24 09:34:19

Looks like an answer that has already been given...

@synan54 2016-01-14 00:43:34

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

@V. Kalyuzhnyu 2018-01-10 07:02:57

Works fine. Thank you

@Peter T. 2015-08-10 11:48:09

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

@Kemat Rochi 2016-04-04 08:08:05

Do you know how to do it backwards, like converting this format DD-MM-YYYY HH:mm:ss to something like this 1439198499 ??

@Peter T. 2016-04-20 13:06:44

Hi Kemat, You can do it via this statement moment('2009-07-15 00:00:00').unix()

@aaj 2016-10-17 09:25:59

My timestamp is in UTC format. Any difference I need to make here for that? How can I have am/pm?

@Laeeq 2018-02-08 07:03:22

You can easily convert timestamp to date usign momentJS, you checkout this coderszine.com/convert-timestamp-to-date-using-javascript

@Adria 2014-10-08 04:41:20

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

@Peter Mortensen 2015-10-05 17:56:43

Regarding "the non-culturally imperialistic way": Don't you mean "the non-culturally and non-imperialistic way"?

@Stephen S. 2016-01-23 20:07:24

Unfortunately this method is not compatible with Safari.

@milkovsky 2014-03-14 15:23:54

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;

@homtg 2013-11-11 10:30:14

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

@martin 2015-02-10 12:33:32

another advantage of moment.js (or similar libs) would be their support of relative time, for messages like "6 hours ago".

@NetOperator Wibby 2015-03-19 16:15:59

In your console.log examples, I was confused about the format due to the /, but it helped me a lot.

@aaj 2016-10-17 09:26:40

My timestamp is in UTC format. Any change I need to make here for that? How can I have am/pm?

@deadrunk 2012-05-10 14:24:29

Another way - from an ISO 8601 date.

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

@Aviram Net 2014-08-03 09:52:54

I get "Object ... has no method 'toISOString'"

@aaj 2016-10-17 09:26:13

My timestamp is in UTC format. Any difference I need to make here for that? How can I have am/pm?

@shams 2012-02-16 14:45:57

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;

@Aron Rotteveel 2009-05-11 08:28:50

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

For more information regarding the Date object, please refer to MDN or the ECMAScript 5 specification.

@nickf 2009-05-13 04:08:06

also you could save yourself a couple of processor ticks by avoiding the need for the large multiplication by just appending three 0s: echo "var date = new Date(" . $timestamp . "000);\n";

@Alnitak 2011-04-19 19:59:39

@nickf multiplications are trivial on modern CPUs - the string concatenation will require a lot more work!

@user656925 2012-01-06 17:08:23

Concatenation should consist of reading memory and writing memory..how could someone design something that takes something simple such as appending and make it more complicated than multiplaction...ask a child to concatenate and they can..multiplicaion is more difficult...plus memory is laid out to work linearly anyawyas...Can someone provide a reference to the @nickf comment?

@Fireblaze 2012-10-04 14:47:49

Actually it will display time in '10:2:2' format, since it does not add an extra 0 before values below 10.

@trejder 2013-07-23 10:10:19

@Fireblaze Then let's get it fixed, shall we? :] See my answer at the bottom.

@SexyBeast 2013-08-07 13:10:42

Any way we can extract the day and date and time, like 21 August, 12:11:23 as well?

@Brad Koch 2013-09-26 15:21:56

@Cupidvogel , sure, check the reference the OP provided, or any of the other answers, which cover month and date as well.

@Brilliand 2013-10-02 21:31:19

@user656925 - Multiplication involves numbers, concatenation involves strings. Computers handle numbers far more efficiently than strings. When string concatenation is done, there's a lot of memory management going on in the background. (However, if you're already doing a string concatenation anyway, then including a few extra characters in one of the strings might actually be less costly on average than the one processor op it takes to multiply two numbers together.)

@Kevin Dice 2014-08-01 06:06:14

Just a minor thing about concatenation: Using .join() is a lot more efficient. However, this this suggests that concatination is becoming more efficient in some cases.

@RobertoNovelo 2015-12-16 22:40:33

This answer is always helpful

@Stallman 2016-03-19 11:53:26

@Alnitak What suggests that string concatenation takes more memory than number computation?

@Alnitak 2016-03-19 11:59:00

@Stallman number computation is the most fundamental thing that computers do, and they're extremely efficient at it, both in memory and runtime. Brilliand's comment above is relevant, although IMHO the very final part of his comment is completely bogus.

@Stallman 2016-03-19 12:46:58

@Brilliand What suggests that string concatenation takes more memory than number computation? I would like to know more about it., is that the property of JS or for all kind of language?

@Brilliand 2016-03-21 23:32:58

@Stallman It's true of all languages (or nearly all, in theory an exotic language could be created that isn't like this - but all the common ones are). A string is stored internally as a pointer to a block of memory where the contents of the string are stored. The pointer itself uses the same amount of memory as most numbers do on the same system, and the memory to store the actual strings is in addition to that. Then when you concatenate the strings, you're most often creating a brand-new string with the combined contents of both strings.

@Stallman 2016-03-22 15:37:30

@Brilliand Here is my understandings: You mean that a string may occupies lots of memory since it consists of lots of chars but the number only takes a little memory. Take C for instance, if the system is 64 OS based, the integer takes 4 bytes; nevertheless the strings may take much more than that.(1*N) And in the process of concatenation, the OS requires to allocate additional memory to accommodate the concatenated strings.

@Brilliand 2016-03-22 17:27:14

@Stallman 64 bits is 8 bytes, but otherwise correct.

@aaj 2016-10-17 09:29:54

My timestamp is in UTC format. Any change I need to make here for that? How can I have am/pm?

@TechWisdom 2015-08-11 22:09:32

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

@Bhaumik Mehta 2015-06-30 14:10:03

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

@Steve Harrison 2009-05-11 08:31:47

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...

@Brad Koch 2012-10-11 21:02:04

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')

@Peter 2018-02-06 20:19:57

I know It was good answer back in a days, but this days extending native js objects is an anti-pattern.

@Grzegorz Gierlik 2009-05-11 08:38:46

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)

@Fireblaze 2012-10-04 15:34:32

// 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());

@trejder 2013-07-23 10:11:00

I don't think you need an extra, separate function, to get a number with trailing zero, whenever this is necessary -- see my answer at the bottom.

@walv 2014-07-18 13:43:37

@trejder, in your example, you DUPLICATE the logic while with extra function you have it in one place. Also you trigger date functon (e.g. getHours()) always two times while here - it is one time call. You can never know how heavy is some library function to be re-executed (however i do believe it is light for dates).

@Bernie 2011-11-01 19:11:18

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.

@Bachi 2013-06-16 14:02:15

for most web solutions, this is the most correct answer, since it uses the client's locale, e.g. 24h vs. 12h am/pm format. For a time string, you would then use: date.toLocaleTimeString()

@VisioN 2016-12-22 15:15:20

It will not happen with toTimeString method. Check here: stackoverflow.com/a/35890537/1249581.

@shomrat 2011-05-21 00:54:49

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;
 }

Related Questions

Sponsored Content

25 Answered Questions

68 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 4908242 View
  • 6173 Score
  • 68 Answer
  • Tags:   javascript arrays

54 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

8 Answered Questions

[SOLVED] Why is subtracting these two times (in 1927) giving a strange result?

  • 2011-07-27 08:15:58
  • Freewind
  • 555621 View
  • 6050 Score
  • 8 Answer
  • Tags:   java date timezone

44 Answered Questions

[SOLVED] How to format a JavaScript date

36 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

88 Answered Questions

[SOLVED] How do JavaScript closures work?

48 Answered Questions

17 Answered Questions

[SOLVED] How to decide when to use Node.js?

Sponsored Content