如何使用 Javascript Date 对象计算东部时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4099238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:22:08  来源:igfitidea点击:

How to calculate eastern time using Javascript Date object?

javascriptdatetimezone

提问by Alex

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 dealis that I want to return the time & date in Eastern Daylight TIme, no matter where in the world the IP is.

我正在处理一个涉及 Javascript 的个人项目,作为该项目的一部分,我想获取当前日期(包括时间)并相应地显示它。没什么大不了的吧?好吧,交易是我想返回东部夏令时的时间和日期,无论 IP 位于世界何处。

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.

如果这是不可能的,您建议使用哪些替代方法?php有这个功能吗?我可以编写一个简单的 php 脚本,它接受一个日期并对其进行转换,但如果可能的话,我想将它保留在 JS 中。

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

我正在考虑最好的方法来做到这一点,但我很感激你能提供的任何帮助。

Thanks!

谢谢!

采纳答案by bobince

JavaScript native Dateobjects 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?

JavaScript 本机Date对象只知道两个时区,UTC 和用户的语言环境时区(即便如此,您可以提取的有关语言环境时区的信息量也是有限的)。你可以在 UTC 工作并减去 4 小时得到 EDT,但你真的总是想要 EDT 而不是 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.

如果您想在 PHP 中的任意区域之间进行时区转换,您需要拖入一个具有自己时区信息的大型库,例如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.

最好将 JavaScript 的内容全部保留在 UTC 中,让 PHP 方面担心使用例如Date/Time 中的时区内容为特定语言环境/时区格式化它。

回答by Harmen

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.

因此,您获取当前时间,添加当前位置的偏移量以获取 UTC 时间,然后返回一个新日期,再次添加某个时区的偏移量。