Convert UNIX timestamp to date time (javascript)
Asked Answered
R

4

25

Timestamp:

1395660658

Code:

//timestamp conversion
exports.getCurrentTimeFromStamp = function(timestamp) {
    var d = new Date(timestamp);
    timeStampCon = d.getDate() + '/' + (d.getMonth()) + '/' + d.getFullYear() + " " + d.getHours() + ':' + d.getMinutes();

    return timeStampCon;
};

This converts the time stamp properly in terms of time format, but the date is always:

17/0/1970

Why - cheers?

Rileyrilievo answered 11/6, 2014 at 19:20 Comment(0)
N
63

You have to multiply by 1000 as JavaScript counts in milliseconds since epoch (which is 01/01/1970), not seconds :

var d = new Date(timestamp*1000);

Reference

Normannormand answered 11/6, 2014 at 19:21 Comment(0)
M
9
function convertTimestamp(timestamp) {
    var d = new Date(timestamp * 1000), // Convert the passed timestamp to milliseconds
        yyyy = d.getFullYear(),
        mm = ('0' + (d.getMonth() + 1)).slice(-2),  // Months are zero based. Add leading 0.
        dd = ('0' + d.getDate()).slice(-2),         // Add leading 0.
        hh = d.getHours(),
        h = hh,
        min = ('0' + d.getMinutes()).slice(-2),     // Add leading 0.
        ampm = 'AM',
        time;

    if (hh > 12) {
        h = hh - 12;
        ampm = 'PM';
    } else if (hh === 12) {
        h = 12;
        ampm = 'PM';
    } else if (hh == 0) {
        h = 12;
    }

    // ie: 2014-03-24, 3:00 PM
    time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm;
    return time;
}

You can get the value by calling like convertTimestamp('1395660658')

Mucus answered 21/6, 2018 at 9:1 Comment(0)
S
4

Because your time is in seconds. Javascript requires it to be in milliseconds since epoch. Multiply it by 1000 and it should be what you want.

//time in seconds
var timeInSeconds = ~(new Date).getTime();
//invalid time
console.log(new Date(timeInSeconds));
//valid time
console.log(new Date(timeInSeconds*1000));
Stav answered 11/6, 2014 at 19:22 Comment(0)
H
2
const timeStamp = 1611214867768;

const dateVal = new Date(timeStamp).toLocaleDateString('en-US');
console.log(dateVal)
Hatten answered 27/1, 2021 at 10:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.