How to calculate eastern time using Javascript Date object?

久未见 提交于 2020-01-02 08:39:08

问题


I'm working on a personal project involving Javascript, and as part of that project, I want to grab the current date (including time) and display it accordingly. No big deal right? Well, the deal is that I want to return the time & date in Eastern Daylight TIme, no matter where in the world the IP is.

If this is not possible, what alternative methods do you suggest? Does php have this functionality? I could write a simple php script that takes a date and converts it, but I want to keep this in JS if at all possible.

I'm trying to think through the best way to do this, but I'd appreciate any help that you could offer.

Thanks!


回答1:


JavaScript native Date objects only know two timezones, UTC and the user's locale timezone (and even then, the amount of information you can extract about the locale timezone is limited). You could work in UTC and subtract 4 hours to get EDT, but do you really always want EDT and not EST?

If you want to do timezone conversions between arbitrary regions in PHP you'll need to drag in a large library with its own timezone information, such as TimezoneJS.

It may be better to keep the JavaScript stuff all in UTC, and let the PHP side worry about formatting it for a particular locale/timezone, using eg the timezone stuff from Date/Time.




回答2:


I found this on the internet, and there are a lot more of these scripts:

function calcTime(offset) {

    // create Date object for current location
    d = new Date();

    // convert to msec
    // add local time zone offset 
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    return new Date(utc + (3600000*offset));

}

So, you get the current time, add the offset of the current location to get UTC time and then you return a new date where you add the offset of a certain time zone again.



来源:https://stackoverflow.com/questions/4099238/how-to-calculate-eastern-time-using-javascript-date-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!