Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - How to make JS date respect local timezone?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...