Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the follow function that properly returns the date in the format required, but the value returned isn't respecting the local timezone. In this case, its 4 hours off. What would I need to modify in this function to make it add the proper offsets based on the users location?

Thanks!

function date_str(seconds) {
    var dt = new Date(1970, 0, 1);
    dt.setSeconds(seconds);
    console.log(dt);
    var month = dt.getMonth() + 1;
    var date = dt.getDate();
    var year = dt.getFullYear();
    var hours = dt.getHours();
    var minutes = dt.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    return month + '/' + date + '/' + year + ', ' + hours + ':' + minutes + ' ' + ampm;
}

Edit: Passing unix time to function 1396450616.505 which converts to Wed, 02 Apr 2014 14:56:56 GMT which returns Sent at 4/2/2014, 2:56 PM from the function itself. The time here is 10:56 AM EST.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
236 views
Welcome To Ask or Share your Answers For Others

1 Answer

Assuming that seconds is a unix epoch (UTC), you should just use

function date_str(seconds) {
    var dt = new Date(seconds*1000);
    console.log(dt);
    …

instead. The get…() methods will respect the local timezone. If you don't want that, you should use the getUTC…() equivalents.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...