Javascript 如何在javascript中将日期时间从用户时区转换为EST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9070604/
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-08-24 08:33:52  来源:igfitidea点击:

How to convert datetime from the users timezone to EST in javascript

javascripthtmldatetime

提问by Carl Weis

I have a web application that has a dynamic javascript calendar, which allows users to set events for a given data and time. I need to push notifications to the users, so I need to convert the date time and timezone they entered, into Eastern Standard Time, so that my notifications are sent out at the correct time.

我有一个具有动态 javascript 日历的 Web 应用程序,它允许用户为给定的数据和时间设置事件。我需要向用户推送通知,因此我需要将他们输入的日期时间和时区转换为东部标准时间,以便在正确的时间发送我的通知。

I would like to do this in javascript, so that when the data time value gets to the php, it's in the right format, before being added to the database.

我想在 javascript 中执行此操作,以便当数据时间值到达 php 时,它在被添加到数据库之前采用正确的格式。

So to summarize, I need to convert a javascript datatime and timezone, which I get by capturing the users datatime, as a full UTC date, to my servers timezone, which is EST - New York.

总而言之,我需要将通过捕获用户数据时间(作为完整的 UTC 日期)获得的 javascript 数据时间和时区转换为我的服务器时区,即 EST - 纽约。

Any help or direction on this matter, would be greatly appreciated. Thanks :)

对此问题的任何帮助或指导,将不胜感激。谢谢 :)

回答by user47900

Pl check this script

请检查此脚本

function convertToServerTimeZone(){

    //EST
    offset = -5.0

    clientDate = new Date();
    utc = clientDate.getTime() + (clientDate.getTimezoneOffset() * 60000);

    serverDate = new Date(utc + (3600000*offset));

    alert (serverDate.toLocaleString());


}

回答by Yevgeny Simkin

I would draw the EST timezone offset into the page while you're rendering it (via PHP) and then grab the UTC time on the client and offset it by the amount you've drawn in. Otherwise, if your server ever moves timezones your page will suddenly be reporting the wrong time.

我会在您渲染页面时(通过 PHP)将 EST 时区偏移量绘制到页面中,然后在客户端上获取 UTC 时间并将其偏移您所绘制的数量。否则,如果您的服务器移动时区,您的页面会突然报错时间。

I just did this recently though, and found that the simplest way to handle this is to actually use mySQL (I'm assuming that's your DB), and just let IT convert the timezone for you while you're entering the date stamp. Unless you're worried this is too tasking and you're trying to absolutely reduce the work your db is doing, I'd go that route, rather than muck about trying to do manual TZ conversions in JS.

不过,我最近才这样做,发现处理这个问题的最简单方法是实际使用 mySQL(我假设那是您的数据库),并在您输入日期戳时让 IT 为您转换时区。除非你担心这太繁重并且你试图绝对减少你的数据库正在做的工作,否则我会走这条路,而不是试图在 JS 中进行手动 TZ 转换。