Javascript 获取特定时区的时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8207655/
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
Get time of specific timezone
提问by aslamdoctor
I am using a JavaScript Date
class & trying to get the current date using getDate()
method. But obviously it is loading system date & time. I am running the code from India but I want to get the date & time of UK using the same method. How can I do that ?
我正在使用 JavaScriptDate
类并尝试使用getDate()
方法获取当前日期。但显然它正在加载系统日期和时间。我正在运行来自印度的代码,但我想使用相同的方法获取英国的日期和时间。我怎样才能做到这一点 ?
采纳答案by Sudhir Bastakoti
If you know the UTC offset then you can pass it and get the time using the following function:
如果您知道 UTC 偏移量,那么您可以传递它并使用以下函数获取时间:
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time for city"+ city +" is "+ nd.toLocaleString();
}
alert(calcTime('Bombay', '+5.5'));
Taken from: Convert Local Time to Another
回答by transistor09
You could use Intl.DateTimeFormat
.
你可以使用Intl.DateTimeFormat
.
let options = {
timeZone: 'Europe/London',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
},
formatter = new Intl.DateTimeFormat([], options);
console.log(formatter.format(new Date()));
Alternatively, if you're formatting just once instead of bulk use Date.prototype.toLocaleDateString()
.
或者,如果您只格式化一次而不是批量使用Date.prototype.toLocaleDateString()
.
(new Date()).toLocaleString([], options)
Unfortunately browsers are notrequired to understand timezones other than UTC, so try
these blocks and figure out an alternative in case it fails, for example fetch the timezone offset from a server.
不幸的是浏览器不要求了解比UTC其他时区,所以try
这些块,并计算出在情况下,它失败的替代,例如取时区从服务器偏移。
回答by Chris
The best way to do this is to use getLocaleString, like this:
最好的方法是使用 getLocaleString,如下所示:
Create a date object:
创建日期对象:
date = new Date(0)
If you are in Berlin, this should convert to this string:
如果你在柏林,这应该转换成这个字符串:
Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
1970 年 1 月 1 日星期四 01:00:00 GMT+0100 (CET)
Get the hours in Athens:
获取雅典的时间:
date.toLocaleString('de-DE', {hour: '2-digit', hour12: false, timeZone: 'Europe/Athens' })
'02'
'02'
Get the hours in Shanghai:
获取上海时间:
date.toLocaleString('de-DE', {hour: '2-digit', hour12: false, timeZone: 'Asia/Shanghai' })
'08'
'08'
回答by Joy Chowdhury
This is Correct way to get ##
这是获得##的正确方法
function getTime(offset)
{
var d = new Date();
localTime = d.getTime();
localOffset = d.getTimezoneOffset() * 60000;
// obtain UTC time in msec
utc = localTime + localOffset;
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
//nd = 3600000 + nd;
utc = new Date(utc);
// return time as a string
$("#local").html(nd.toLocaleString());
$("#utc").html(utc.toLocaleString());
}
回答by kevinji
You can use getUTCDate()
and the related getUTC...()
methods to access a time based off UTC time, and then convert.
您可以使用getUTCDate()
和相关getUTC...()
方法来访问基于 UTC 时间的时间,然后进行转换。
If you wish, you can use valueOf()
, which returns the number of seconds, in UTC, since the Unix epoch, and work with that, but it's likely going to be much more involved.
如果你愿意,你可以使用valueOf()
,它返回自 Unix 时代以来的 UTC 秒数,并使用它,但它可能会涉及更多。
回答by Stein G. Strindhaug
If it's really important that you have the correct date and time; it's best to have a service on your server (which you of course have running in UTC) that returns the time. You can then create a new Date on the client and compare the values and if necessary adjust all dates with the offset from the server time.
如果您拥有正确的日期和时间真的很重要;最好在您的服务器(您当然在 UTC 中运行)上有一个返回时间的服务。然后,您可以在客户端上创建一个新日期并比较这些值,并在必要时调整所有日期与服务器时间的偏移量。
Why do this? I've had bug reports that was hard to reproduce because I could not find the error messages in the server log, until I noticed that the bug report was mailed two days afterI'd received it. You can probablytrust the browser to correctly handle time-zone conversion when being sent a UTC timestamp, but you obviously cannot trust the users to have their system clock correctly set. (If the users have their timezone incorrectly set too, there is not really any solution; other than printing the current server time in "local" time)
为什么要这样做?我有过很难重现的错误报告,因为我在服务器日志中找不到错误消息,直到我注意到错误报告是在我收到两天后邮寄的。您可能会相信浏览器在发送 UTC 时间戳时会正确处理时区转换,但您显然不能相信用户会正确设置他们的系统时钟。(如果用户的时区也设置不正确,则实际上没有任何解决方案;除了以“本地”时间打印当前服务器时间)
回答by Kieran
before you get too excited this was written in 2011
在你太兴奋之前这是在 2011 年写的
if I were to do this these days I would use Intl.DateTimeFormat. Here is a link to give you an idea of what type of support this had in 2011
如果这些天我要这样做,我会使用Intl.DateTimeFormat。这是一个链接,可让您了解它在 2011 年获得的支持类型
original answer now (very) outdated
现在(非常)过时的原始答案
Date.getTimezoneOffset()
Date.getTimezoneOffset()
The getTimezoneOffset() method returns the time difference between Greenwich Mean Time (GMT) and local time, in minutes.
getTimezoneOffset() 方法返回格林威治标准时间 (GMT) 与本地时间之间的时差(以分钟为单位)。
For example, If your time zone is GMT+2, -120 will be returned.
例如,如果您的时区是 GMT+2,则返回 -120。
Note: This method is always used in conjunction with a Date object.
注意:此方法始终与 Date 对象结合使用。
var d = new Date()
var gmtHours = -d.getTimezoneOffset()/60;
document.write("The local time zone is: GMT " + gmtHours);
//output:The local time zone is: GMT 11
回答by CommunistPancake
The .getTimezoneOffset()
method should work. This will get the time between your time zone and GMT. You can then calculate to whatever you want.
该.getTimezoneOffset()
方法应该有效。这将获得您的时区和格林威治标准时间之间的时间。然后你可以计算任何你想要的。
回答by jerjer
short answer from client-side: NO, you have to get it from the server side.
客户端的简短回答:不,您必须从服务器端获取它。