f1nn
f1nn

Reputation: 7047

Node.JS - Converting UNIX Timestamp to Time - timezones shift

I have a function, that converts timestamp to time:

function convertUnixTimeToTime(UNIX_timestamp) {
    var a = new Date(UNIX_timestamp);
    var fin_hour = String(a.getHours())
    if (fin_hour.length == 1) {
        fin_hour = '0' + fin_hour;
    }
    var fin_minutes = String(a.getMinutes())
    if (fin_minutes.length == 1) {
        fin_minutes = '0' + fin_minutes;
    }
    var time = fin_hour + ':' + fin_minutes;
    return time;
}

I'm tesing my app locally, my computer's timeshift is +4. When I try to get current time from node app:

console.log('Current time is: ' + convertUnixTimeToTime(new Date().getTime()));

I get my current local time. As I supposed, Date().getTime() should return absolute UNIX time in milliseconds. My function convertUnixTimeToTime() does not specify any time shift, that's why I should get clear time without any shifts. Why am I getting shifted +4 time? Thanks.

Upvotes: 0

Views: 6474

Answers (2)

Aaron Dufour
Aaron Dufour

Reputation: 17505

The getHours and getMinutes functions always return local time. The new Date(new Date().getTime()) is confusing more than anything else - its the same as new Date() - it does not change anything about timezones.

To get what you're looking for, use getUTCHours and getUTCMinutes.

Upvotes: 2

lanzz
lanzz

Reputation: 43168

Because Date.getHours() and Date.getMinutes() by definition return local time?

Upvotes: 1

Related Questions