roflwaffle
roflwaffle

Reputation: 30666

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.

Upvotes: 1681

Views: 2641623

Answers (30)

Apurv
Apurv

Reputation: 123

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"

Upvotes: 1

Aron Rotteveel
Aron Rotteveel

Reputation: 83203

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.

Upvotes: 2359

Dan Alboteanu
Dan Alboteanu

Reputation: 10252

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

Upvotes: 244

Saitejareddy
Saitejareddy

Reputation: 361

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

Upvotes: 11

B. Martin
B. Martin

Reputation: 1163

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

Upvotes: 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

Upvotes: 3

John Slegers
John Slegers

Reputation: 47121

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.

Upvotes: 7

Shahnad S
Shahnad S

Reputation: 1167

Try this :

      new Date(1638525320* 1e3).toISOString()  //2021-12-03T09:55:20.000Z

Upvotes: 5

User
User

Reputation: 79

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>

Upvotes: 2

VisioN
VisioN

Reputation: 145458

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.

Upvotes: 136

James Ikubi
James Ikubi

Reputation: 2948

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

Upvotes: 29

Valix85
Valix85

Reputation: 793

In moment you must use unix timestamp:

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

Upvotes: 33

Ashish Gupta
Ashish Gupta

Reputation: 1241

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

Upvotes: 7

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92657

Shortest

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

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

console.log(time);

Upvotes: 5

Amey Vartak
Amey Vartak

Reputation: 339

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.

Upvotes: 2

deadrunk
deadrunk

Reputation: 14155

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

Upvotes: 17

synan54
synan54

Reputation: 658

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

Upvotes: 13

xgqfrms
xgqfrms

Reputation: 12206

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"


Upvotes: 5

Luis David
Luis David

Reputation: 784

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"

Upvotes: 41

tivoni
tivoni

Reputation: 2020

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

Upvotes: 3

shomrat
shomrat

Reputation: 3909

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

Upvotes: 381

Basj
Basj

Reputation: 46303

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

Upvotes: 13

Peter Tadros
Peter Tadros

Reputation: 9307

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

Upvotes: 19

Adria
Adria

Reputation: 9061

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

Upvotes: 10

milkovsky
milkovsky

Reputation: 8862

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;

Upvotes: 3

homtg
homtg

Reputation: 1999

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

Upvotes: 37

shams
shams

Reputation: 51

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;

Upvotes: 5

TechWisdom
TechWisdom

Reputation: 4315

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

Upvotes: 8

Bhaumik Mehta
Bhaumik Mehta

Reputation: 373

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

Upvotes: 4

Steve Harrison
Steve Harrison

Reputation: 125640

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

Upvotes: 303

Related Questions