26

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?

4 Answers 4

64

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

3

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

Comments

2
const timeStamp = 1611214867768;

const dateVal = new Date(timeStamp).toLocaleDateString('en-US');
console.log(dateVal)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.