Convert a Unix timestamp to time in JavaScript

2,094,073

Solution 1

let unix_timestamp = 1549312452
// 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);

console.log(formattedTime);

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

Solution 2

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

Solution 3

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

Solution 4

Use:

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

and for time:

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

see Date.prototype.toLocaleDateString()

Solution 5

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:

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"

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:

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

console.log( format_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.

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

Share:
2,094,073
roflwaffle
Author by

roflwaffle

Updated on July 20, 2022

Comments

  • roflwaffle
    roflwaffle almost 2 years

    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.

  • nickf
    nickf almost 15 years
    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
    Alnitak about 13 years
    @nickf multiplications are trivial on modern CPUs - the string concatenation will require a lot more work!
  • shomrat
    shomrat almost 13 years
    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.
  • Admin
    Admin over 12 years
    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
    Fireblaze over 11 years
    Actually it will display time in '10:2:2' format, since it does not add an extra 0 before values below 10.
  • Bachi
    Bachi almost 11 years
    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()
  • trejder
    trejder almost 11 years
    @Fireblaze Then let's get it fixed, shall we? :] See my answer at the bottom.
  • trejder
    trejder almost 11 years
    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.
  • SexyBeast
    SexyBeast over 10 years
    Any way we can extract the day and date and time, like 21 August, 12:11:23 as well?
  • Brad Koch
    Brad Koch over 10 years
    @Cupidvogel , sure, check the reference the OP provided, or any of the other answers, which cover month and date as well.
  • Brilliand
    Brilliand over 10 years
    @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.)
  • walv
    walv almost 10 years
    @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).
  • Kevin Dice
    Kevin Dice over 9 years
    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.
  • Aviram Netanel
    Aviram Netanel over 9 years
    I get "Object ... has no method 'toISOString'"
  • user1985189
    user1985189 over 9 years
    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
    jcampbell1 over 9 years
    Bug: getMonth() returns a month number between 0 and 11, thus a.getMonth() - 1 is wrong.
  • martin
    martin about 9 years
    another advantage of moment.js (or similar libs) would be their support of relative time, for messages like "6 hours ago".
  • NetOperator Wibby
    NetOperator Wibby about 9 years
    In your console.log examples, I was confused about the format due to the /, but it helped me a lot.
  • Peter Mortensen
    Peter Mortensen over 8 years
    Regarding "the non-culturally imperialistic way": Don't you mean "the non-culturally and non-imperialistic way"?
  • RobertoNovelo
    RobertoNovelo over 8 years
    This answer is always helpful
  • Stephen S.
    Stephen S. over 8 years
    Unfortunately this method is not compatible with Safari.
  • Alston
    Alston about 8 years
    @Alnitak What suggests that string concatenation takes more memory than number computation?
  • Alnitak
    Alnitak about 8 years
    @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.
  • Alston
    Alston about 8 years
    @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
    Brilliand about 8 years
    @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.
  • Alston
    Alston about 8 years
    @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.
  • Kemat Rochi
    Kemat Rochi about 8 years
    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.
    Peter T. about 8 years
    Hi Kemat, You can do it via this statement moment('2009-07-15 00:00:00').unix()
  • codec
    codec over 7 years
    My timestamp is in UTC format. Any difference I need to make here for that? How can I have am/pm?
  • codec
    codec over 7 years
    My timestamp is in UTC format. Any difference I need to make here for that? How can I have am/pm?
  • codec
    codec over 7 years
    My timestamp is in UTC format. Any change I need to make here for that? How can I have am/pm?
  • codec
    codec over 7 years
    My timestamp is in UTC format. Any change I need to make here for that? How can I have am/pm?
  • VisioN
    VisioN over 7 years
    It will not happen with toTimeString method. Check here: stackoverflow.com/a/35890537/1249581.
  • Steve Chamaillard
    Steve Chamaillard about 7 years
    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
    Steve Chamaillard about 7 years
    I've offered an edit for your answer that ignores any timezone, so it'll always show the right formatted value !
  • VisioN
    VisioN about 7 years
    @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.
  • Vlad
    Vlad over 6 years
    Works fine. Thank you
  • Peter
    Peter about 6 years
    I know It was good answer back in a days, but this days extending native js objects is an anti-pattern.
  • Laeeq
    Laeeq about 6 years
    You can easily convert timestamp to date usign momentJS, you checkout this coderszine.com/convert-timestamp-to-date-using-javascript
  • Wolfgang
    Wolfgang almost 6 years
    This is a command to get the date (M/D/YYYY), not the time (HH/MM/SS) as requested.
  • SamGoody
    SamGoody almost 6 years
    Even shorter with ES6: let time = s => new Date(s * 1e3).toISOString().slice(-13, -5)
  • Robin Métral
    Robin Métral about 5 years
    moment.js is waaay overkill for such a small thing to do and will affect your performance. Use native methods instead, cf. Dan Alboteanu's answer
  • ibodi
    ibodi almost 5 years
    It doesn't work (anymore?) in node js format is not a function. But this apparently works: stackoverflow.com/a/34015511/7550772
  • keanu_reeves
    keanu_reeves over 4 years
    when using this with PHP unix timestamps i get +5h than the actual time for some reason :/
  • bitfiddler
    bitfiddler over 4 years
    @keanu_reeves - sounds like you are in eastern US time zone and the timestamps are UTC. Try removing the .slice(0,19) and I think you will see the timezone of the result is Z (Zulu).
  • camillo777
    camillo777 about 4 years
    just a note, the number "1504095567183" is unix_timestamp * 1000
  • Orici
    Orici about 4 years
    This is not an Unix Timestamp: 1435986900000 / This is an Unix Timestamp: 1435986900
  • abidinberkay
    abidinberkay about 4 years
    this solution works for me but how can i take the month like Feb Mar Apr instead of number ?
  • Sean
    Sean almost 4 years
    In addition, toLocaleString includes both date and time.
  • Kamil Kiełczewski
    Kamil Kiełczewski almost 4 years
    for timestamp=1592426697 gives wrong number of hours (=442340) - can you fix it?
  • Daniel
    Daniel over 3 years
    @Alston It's really a lot more complicated than that. Strings are stored as a stack pointer to an array, the contents of which are stored on the heap (whereas integers are stored directly on the stack). That means that every call to a string also involves a dereferencing operation. Of course, computers do this quite quickly. But each of these strings is also allocated additional memory to allow for mutation, which can balloon the amount of memory required.
  • lys
    lys about 3 years
    Both aren't working in Safari iOS 13 using the timestamp from navigator.geolocation
  • Flight Dude
    Flight Dude about 3 years
    This is brilliant. Thanks!
  • Curtis
    Curtis almost 3 years
    Don't need a list of month names, javascript has that, even in IE. var month = a.toLocaleDateString(undefined, {month: 'short'})
  • Tony Borchert
    Tony Borchert over 2 years
    I don't know if it will help the discussion, but beware that if you give the Date constructor a number, it knows exactly how to interpret it. But if you give the Date constructor a string, it would have to validate it, as there are dozens of possible string date time constructs that are all equally as valid, so there would be some validation necessary while the number as an input does not require any
  • NoxFly
    NoxFly over 2 years
    String.substr() is deprecated nowadays. Use slice instead, which can also cover the negative index.
  • Alex78191
    Alex78191 about 2 years
    @ibodi it's library
  • August
    August about 2 years
    To get only date part: let str = date.toISOString().split('T')[0];
  • Vasyl Gutnyk
    Vasyl Gutnyk about 2 years
    can you explain how does it work? what is 1e3 and why we multiple it?