How to calculate eastern time using Javascript Dat

2019-05-10 05:03发布

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!

2条回答
Fickle 薄情
2楼-- · 2019-05-10 05:30

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.

查看更多
够拽才男人
3楼-- · 2019-05-10 05:42

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.

查看更多
登录 后发表回答