Convert a Unix timestamp to time in JavaScript
Asked Answered
H

35

1658

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.

Hanzelin answered 11/5, 2009 at 8:23 Comment(5)
Just multiply by 1000 since JS timestamps are in milliseconds and PHP delivers in seconds.Adaxial
Here is a very useful link with different date format: timestamp.online/article/… Combine with the multiplication by 1000 and it gets the job done!Perreault
See this how I have achieved: https://mcmap.net/q/37230/-function-to-convert-timestamp-to-human-date-in-javascript-duplicateAngelangela
If you have a string in a different date format, see Parsing a string to a date in JavaScript.Pyorrhea
dt=new Date(1234567890 * 1000).toLocaleString(); gives date+time — or use .toLocaleDateString() or .toLocaleTimeString())Giblet
P
2327

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.

Pendragon answered 11/5, 2009 at 8:28 Comment(20)
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";Horseback
@Horseback multiplications are trivial on modern CPUs - the string concatenation will require a lot more work!Lignite
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 @Horseback comment?Fanny
Actually it will display time in '10:2:2' format, since it does not add an extra 0 before values below 10.Harper
@Harper Then let's get it fixed, shall we? :] See my answer at the bottom.Cassidy
Any way we can extract the day and date and time, like 21 August, 12:11:23 as well?Bibbie
@Cupidvogel , sure, check the reference the OP provided, or any of the other answers, which cover month and date as well.Scruggs
@Fanny - 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.)Starvation
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.Reddick
@Lignite What suggests that string concatenation takes more memory than number computation?Terzetto
@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.Lignite
@Starvation 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?Terzetto
@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.Starvation
@Starvation 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.Terzetto
My timestamp is in UTC format. Any change I need to make here for that? How can I have am/pm?Dilute
@Terzetto 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.Fez
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 anyFerino
String.substr() is deprecated nowadays. Use slice instead, which can also cover the negative index.Chaliapin
To get only date part: let str = date.toISOString().split('T')[0];Relly
Please modify the code to use String.substring() instead of String.substr(). It's deprecated.Frobisher
I
380

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));
Ironwood answered 21/5, 2011 at 0:44 Comment(4)
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.Ironwood
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();Alboin
Bug: getMonth() returns a month number between 0 and 11, thus a.getMonth() - 1 is wrong.Urbannal
Don't need a list of month names, javascript has that, even in IE. var month = a.toLocaleDateString(undefined, {month: 'short'})Sketchy
U
296

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...
Unwritten answered 11/5, 2009 at 8:31 Comment(1)
this is so much simpler. why are all the other answers so complicatedMount
W
234

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

Whaler answered 9/5, 2018 at 14:4 Comment(3)
This is a command to get the date (M/D/YYYY), not the time (HH/MM/SS) as requested.Gourmont
just a note, the number "1504095567183" is unix_timestamp * 1000Malaysia
In addition, toLocaleString includes both date and time.Jocelyn
H
134

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.

Hearst answered 9/3, 2016 at 11:37 Comment(5)
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 !Camaraderie
I've offered an edit for your answer that ignores any timezone, so it'll always show the right formatted value !Camaraderie
@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.Hearst
Even shorter with ES6: let time = s => new Date(s * 1e3).toISOString().slice(-13, -5)Capitular
Both aren't working in Safari iOS 13 using the timestamp from navigator.geolocationMyceto
S
89

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')
Scruggs answered 11/10, 2012 at 21:2 Comment(3)
I know It was good answer back in a days, but this days extending native js objects is an anti-pattern.Yesteryear
It doesn't work (anymore?) in node js format is not a function. But this apparently works: https://mcmap.net/q/37232/-how-do-i-format-a-date-in-javascriptNecklace
@Necklace it's libraryFortyfour
C
40

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

console.log(new Date(1549312452 * 1000).toISOString().slice(0, 19).replace('T', ' '));
// "2019-02-04 20:34:12"
Chery answered 4/2, 2019 at 20:44 Comment(2)
when using this with PHP unix timestamps i get +5h than the actual time for some reason :/Petrillo
@Petrillo - 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).Heidiheidie
N
37

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") );
Nobby answered 11/11, 2013 at 10:30 Comment(4)
another advantage of moment.js (or similar libs) would be their support of relative time, for messages like "6 hours ago".Ostensory
In your console.log examples, I was confused about the format due to the /, but it helped me a lot.Tasiatasiana
My timestamp is in UTC format. Any change I need to make here for that? How can I have am/pm?Dilute
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 answerSlime
A
33

In moment you must use unix timestamp:

const dateTimeString = moment.unix(1466760005).format("DD-MM-YYYY HH:mm:ss");
Astrogation answered 24/6, 2016 at 9:26 Comment(0)
K
29

This works with PHP timestamps

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

Kelbee answered 5/11, 2018 at 13:25 Comment(0)
G
27

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)
Gathering answered 11/5, 2009 at 8:38 Comment(0)
C
19

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");
Comstockery answered 10/8, 2015 at 11:48 Comment(4)
Do you know how to do it backwards, like converting this format DD-MM-YYYY HH:mm:ss to something like this 1439198499 ??Jhelum
Hi Kemat, You can do it via this statement moment('2009-07-15 00:00:00').unix()Comstockery
My timestamp is in UTC format. Any difference I need to make here for that? How can I have am/pm?Dilute
You can easily convert timestamp to date usign momentJS, you checkout this coderszine.com/convert-timestamp-to-date-using-javascriptMatchboard
G
17

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.

Gaptoothed answered 1/11, 2011 at 19:11 Comment(2)
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()Malaya
It will not happen with toTimeString method. Check here: https://mcmap.net/q/37093/-convert-a-unix-timestamp-to-time-in-javascript.Hearst
M
17

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]);
Maurita answered 10/5, 2012 at 14:24 Comment(2)
I get "Object ... has no method 'toISOString'"Colorist
My timestamp is in UTC format. Any difference I need to make here for that? How can I have am/pm?Dilute
S
13
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
Shinar answered 14/1, 2016 at 0:43 Comment(1)
Works fine. Thank youLark
H
13

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;
}
Humiliating answered 6/11, 2016 at 11:51 Comment(0)
D
10

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 ) ) );
Deportation answered 8/10, 2014 at 4:41 Comment(2)
Regarding "the non-culturally imperialistic way": Don't you mean "the non-culturally and non-imperialistic way"?Incarnate
Unfortunately this method is not compatible with Safari.Somnambulism
C
10

There are multiple ways to convert unix timestamp to time (HH/MM/SS)

  1. Using new Date() - this is in-built in javascript
  2. moment package - this is a famous node module, but this is going to deprecate.
  3. dayjs package - this is one of the latest and fast growing node module

Using new Date()

const dateTimeStr = new Date(1504052527183).toLocaleString()
const result = (dateTimeStr.split(", ")[1]).split(":").join("/")
console.log(result)

Using moment

const moment = require('moment')
const timestampObj = moment.unix(1504052527183);
const result = timestampObj.format("HH/mm/ss")
console.log(result);

Using day.js

const dayjs = require('dayjs')
const result = dayjs(1504052527183).format("HH/mm/ss")
console.log(result);

you can check the timestamp to date time conversion with an online time conversion tool

Carr answered 5/2, 2022 at 9:37 Comment(0)
V
8

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
Vichyssoise answered 11/8, 2015 at 22:9 Comment(0)
S
7

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.

Stemma answered 24/2, 2017 at 12:33 Comment(0)
H
6
// 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());
Harper answered 4/10, 2012 at 15:34 Comment(2)
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.Cassidy
@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).Wollastonite
C
6

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
Conney answered 4/7, 2017 at 6:59 Comment(2)
This is not an Unix Timestamp: 1435986900000 / This is an Unix Timestamp: 1435986900Perspicacious
this solution works for me but how can i take the month like Feb Mar Apr instead of number ?Sension
I
5
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;
 }
Ironwood answered 21/5, 2011 at 0:54 Comment(0)
W
5

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;
Wigging answered 16/2, 2012 at 14:45 Comment(0)
E
5

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"


Employment answered 10/1, 2020 at 4:0 Comment(0)
J
5

Shortest

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

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

console.log(time);
Jewbaiting answered 17/6, 2020 at 20:28 Comment(0)
F
5

Try this :

      new Date(1638525320* 1e3).toISOString()  //2021-12-03T09:55:20.000Z
Foliation answered 3/12, 2021 at 13:36 Comment(2)
can you explain how does it work? what is 1e3 and why we multiple it?Joanejoanie
@VasylGutnyk new Date expects time in milliseconds, but we usually hus it in seconds, so we multiply it by 1000. 1e3 is the same as 1000Peerless
S
4
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
Scamp answered 30/6, 2015 at 14:10 Comment(0)
H
3

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;
Hamford answered 14/3, 2014 at 15:23 Comment(1)
for timestamp=1592426697 gives wrong number of hours (=442340) - can you fix it?Mn
N
3

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

const timeStrGet = date => {
    const milliSecsStr = date.getMilliseconds().toString().padStart(3, '0') ;
    return `${date.toLocaleTimeString('it-US')}.${milliSecsStr}`;
};

setInterval(() => console.log(timeStrGet(new Date())), 299);
Nyhagen answered 29/1, 2019 at 15:11 Comment(0)
K
3

You can play around with the format (source):

const date = new Date(yourTimestamp).toLocaleDateString('de-DE', {
    weekday: 'long',
    day: '2-digit',
    month: 'long',
    year: 'numeric'
})

Result:

Sonntag, 01. Januar 2023
Kop answered 20/7, 2022 at 16:17 Comment(0)
F
2

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

function ConvertUnixTimeToDateForLeap(UNIX_Timestamp) {
    var dateObj = new Date(1980, 0, 1, 0, 0, 0, 0);
    dateObj.setSeconds(dateObj.getSeconds() + UNIX_Timestamp);
    return dateObj;  
}

document.body.innerHTML = 'TimeStamp : ' + ConvertUnixTimeToDateForLeap(1269700200);

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

Fostoria answered 3/2, 2020 at 4:46 Comment(0)
N
2

If Timestamp is a numeric integer string, it must be converted to integer number first:

<!DOCTYPE html>

<input type="text" id="Date_Timestamp" size="50" oninput='
document.getElementById("Date_Timestamp_Conversion").innerText = 
new Date(this.value) + " _ (Converted to Local Time) \n" +
new Date(this.value).toString() + " _ (Converted to Local Time) \n" +
new Date(this.value).toUTCString() + " _ (Converted to Universal Time, UTC, GMT, GMT+0, GMT-0) \n" +
Date.parse(this.value) + " _ (Timestamp _ The Date is first converted to Universal Time, then converted to Timestamp)\n" +
( isNaN(this.value) ? "Not a Number _ (Timestamp to Local Time)" : new Date(parseInt(this.value)) + " _ (Converted to Local Time)" ) + "\n" +
( isNaN(this.value) ? "Not a Number _ (Timestamp to Universal Time)" : new Date(parseInt(this.value)).toUTCString() + " _ (Converted to Universal Time)" ) + "\n" +
"";'>
<br>
<span id="Date_Timestamp_Conversion">(Type\Paste a "Date" or "Timestamp" in the input box above!)<br></span>
<br>
2021/03/19 = March 19 2021 _ ("Year/Month/Day" _ Supported)<br>
03/19/2021 = March 19 2021 _ ("Month/Day/Year" _ Supported)<br>
19/03/2021 = Invalid Date _ ("Day/Month/Year" _ Not Supported)<br>
<br>

<script>

d = new Date();
document.getElementById("Date_Timestamp").value =
d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate() + ", " + d.toLocaleTimeString([], {hour12:false, timeZoneName:"short"});

</script>
Nikolia answered 21/3, 2021 at 6:29 Comment(0)
D
2

I was looking for a simple, short solution to this problem as well. That's why I created this function.

You can easily expand the functionality. This function has all the options I need. It's basically doing the same as the php date function.

function date_format(unix_timestamp,format){
    const date=new Date(unix_timestamp*1000);
    const dateObject={
        'Y' : date.getFullYear(),
        'm' : String(date.getMonth()).padStart(2,'0'),
        'd' : String(date.getDate()).padStart(2,'0'),
        'H' : String(date.getHours()).padStart(2,'0'),
        'i' : String(date.getMinutes()).padStart(2,'0'),
        's' : String(date.getSeconds()).padStart(2,'0'),
    };
    var dateString='';
    for (let char of format) {
        if(char in dateObject){
            dateString+=dateObject[char];
        }else{
            dateString+=char;
        }
    }
    return dateString;
}

console.log(date_format(1667127654,'H/i/s')); // 12/00/54
console.log(date_format(1667127654,'Y-m-d H:i:s')); // 2022-10-30 12:00:54
console.log(date_format(1667127654,'d.m.Y')); // 30.10.2022
console.log(date_format(1667127654,'H:i:s')); // 12:00:54
Domenic answered 30/10, 2022 at 11:30 Comment(0)
L
0

Example 1

 var d =new Date("2023-01-22 00:00:00").toLocaleDateString('en-IN');
// "22/01/2023"

 var d = new Date("2023-01-22 00:00:00").toLocaleString('en-IN')
//"22/01/2023, 00:00:00"


const date = new Date("2023-01-22 00:00:00");
console.log(date.getDate() + '/' +  date.getMonth()+1 + '/' + date.getFullYear());

Example 2:

const date = moment.unix("1666632563").format("DD/MM/YYYY");
console.log(date);

//10/12/2024

Example 3:

const date = new Date(1666632563517);
console.log(date.toLocaleString());

//"10/24/2022, 10:59:23 PM"

Example 4:

const date = new Date("2023-01-22 00:00:00");
console.log(date.getDate() + '/' +  date.getMonth()+1 + '/' + date.getFullYear());
//> "22/01/2023"
Lolland answered 5/2, 2024 at 10:39 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.