Convert a Unix timestamp to time in JavaScript
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.
roflwaffle
Updated on July 20, 2022Comments
-
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.-
ankr over 6 yearsJust multiply by 1000 since JS timestamps are in milliseconds and PHP delivers in seconds.
-
Kevin Lemaire about 4 yearsHere is a very useful link with different date format: timestamp.online/article/… Combine with the multiplication by 1000 and it gets the job done!
-
Hidayt Rahman over 3 yearsSee this how I have achieved: stackoverflow.com/a/64089456/2927228
-
Sebastian Simon about 2 yearsIf you have a string in a different date format, see Parsing a string to a date in JavaScript.
-
-
nickf almost 15 yearsalso 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 about 13 years@nickf multiplications are trivial on modern CPUs - the string concatenation will require a lot more work!
-
shomrat almost 13 yearsfor 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 over 12 yearsConcatenation 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 over 11 yearsActually it will display time in '10:2:2' format, since it does not add an extra 0 before values below 10.
-
Bachi almost 11 yearsfor 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 almost 11 years@Fireblaze Then let's get it fixed, shall we? :] See my answer at the bottom.
-
trejder almost 11 yearsI 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 over 10 yearsAny way we can extract the day and date and time, like 21 August, 12:11:23 as well?
-
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 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 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 over 9 yearsJust 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 over 9 yearsI get "Object ... has no method 'toISOString'"
-
user1985189 over 9 yearsI 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 over 9 yearsBug:
getMonth()
returns a month number between 0 and 11, thusa.getMonth() - 1
is wrong. -
martin about 9 yearsanother advantage of moment.js (or similar libs) would be their support of relative time, for messages like "6 hours ago".
-
NetOperator Wibby about 9 yearsIn your
console.log
examples, I was confused about the format due to the/
, but it helped me a lot. -
Peter Mortensen over 8 yearsRegarding "the non-culturally imperialistic way": Don't you mean "the non-culturally and non-imperialistic way"?
-
RobertoNovelo over 8 yearsThis answer is always helpful
-
Stephen S. over 8 yearsUnfortunately this method is not compatible with Safari.
-
Alston about 8 years@Alnitak What suggests that string concatenation takes more memory than number computation?
-
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 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 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 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 about 8 yearsDo you know how to do it backwards, like converting this format DD-MM-YYYY HH:mm:ss to something like this 1439198499 ??
-
Peter T. about 8 yearsHi Kemat, You can do it via this statement moment('2009-07-15 00:00:00').unix()
-
codec over 7 yearsMy timestamp is in UTC format. Any difference I need to make here for that? How can I have am/pm?
-
codec over 7 yearsMy timestamp is in UTC format. Any difference I need to make here for that? How can I have am/pm?
-
codec over 7 yearsMy timestamp is in UTC format. Any change I need to make here for that? How can I have am/pm?
-
codec over 7 yearsMy timestamp is in UTC format. Any change I need to make here for that? How can I have am/pm?
-
VisioN over 7 yearsIt will not happen with
toTimeString
method. Check here: stackoverflow.com/a/35890537/1249581. -
Steve Chamaillard about 7 yearsI'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 about 7 yearsI've offered an edit for your answer that ignores any timezone, so it'll always show the right formatted value !
-
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 usetoISOString
instead, sincetoGMTString
is deprecated and may return different results on different platforms. -
Vlad over 6 yearsWorks fine. Thank you
-
Peter about 6 yearsI know It was good answer back in a days, but this days extending native js objects is an anti-pattern.
-
Laeeq about 6 yearsYou can easily convert timestamp to date usign momentJS, you checkout this coderszine.com/convert-timestamp-to-date-using-javascript
-
Wolfgang almost 6 yearsThis is a command to get the date (M/D/YYYY), not the time (HH/MM/SS) as requested.
-
SamGoody almost 6 yearsEven shorter with ES6: let time = s => new Date(s * 1e3).toISOString().slice(-13, -5)
-
Robin Métral about 5 yearsmoment.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 almost 5 yearsIt doesn't work (anymore?) in node js
format is not a function
. But this apparently works: stackoverflow.com/a/34015511/7550772 -
keanu_reeves over 4 yearswhen using this with PHP unix timestamps i get +5h than the actual time for some reason :/
-
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 about 4 yearsjust a note, the number "1504095567183" is unix_timestamp * 1000
-
Orici about 4 yearsThis is not an Unix Timestamp: 1435986900000 / This is an Unix Timestamp: 1435986900
-
abidinberkay about 4 yearsthis solution works for me but how can i take the month like Feb Mar Apr instead of number ?
-
Sean almost 4 yearsIn addition,
toLocaleString
includes both date and time. -
Kamil Kiełczewski almost 4 yearsfor
timestamp=1592426697
gives wrong number of hours (=442340) - can you fix it? -
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 about 3 yearsBoth aren't working in Safari iOS 13 using the timestamp from
navigator.geolocation
-
Flight Dude about 3 yearsThis is brilliant. Thanks!
-
Curtis almost 3 yearsDon't need a list of month names, javascript has that, even in IE. var month = a.toLocaleDateString(undefined, {month: 'short'})
-
Tony Borchert over 2 yearsI 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 over 2 yearsString.substr() is deprecated nowadays. Use slice instead, which can also cover the negative index.
-
Alex78191 about 2 years@ibodi it's library
-
August about 2 yearsTo get only date part:
let str = date.toISOString().split('T')[0];
-
Vasyl Gutnyk about 2 yearscan you explain how does it work? what is 1e3 and why we multiple it?