[英]Incorrect timezone from server side to Javascript
I have this method in the C# (server) side: 我在C#(服务器)端有此方法:
protected double GetAccountTime()
{
return ((DateTime)unit.SomeMethod(DateTime.UtcNow))
.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
.TotalMilliseconds;
}
My local machine time is Eastern, but my application's account time is Mountain. 我的本地计算机时间是东部时间,但是我的应用程序的帐户时间是Mountain。 So I want to change it to Eastern to Mountain time.
因此,我想将其更改为“东部到山区”时间。
unit.SomeMethod(...)
just takes the current local time (Eastern) and converts it to account time (Mountain). unit.SomeMethod(...)
仅采用当前本地时间(东部)并将其转换为帐户时间(山)。
In the Javascript side: 在Javascript方面:
var now = new Date(<%=GetAccountTime()%>);
alert(now);//doesn't consider the time to be UTC, need to convert
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
alert("UTC: " + now_utc);
The first alert statement gives me Thu Jun 12 2014 09:30:42 GMT-0400 (Eastern Standard Time)
which is incorrect. 第一个警报声明给了我
Thu Jun 12 2014 09:30:42 GMT-0400 (Eastern Standard Time)
,这是不正确的。 I convert the time to UTC, so second alert statement gives me UTC: Thu Jun 12 2014 13:30:42 GMT-0400 (Eastern Standard Time)
. 我将时间转换为UTC,因此第二次警报声明为我提供
UTC: Thu Jun 12 2014 13:30:42 GMT-0400 (Eastern Standard Time)
。 This is correct as far as time goes, but the time zone is still Eastern. 就时间而言,这是正确的,但时区仍为东部。 Does anyone why and how can I fix this?
有人为什么以及如何解决这个问题?
What my application does (at request of @JonSkeet): 我的应用程序做什么(应@JonSkeet的要求):
A Date
object doesn't have any concept of a time zone. Date
对象没有任何时区概念。 It always represents a number of milliseconds since the Unix epoch. 自Unix时代以来,它始终代表毫秒数。
You don't need to do any conversions - you've got the right point in time. 您不需要进行任何转换-您有正确的时间点。 (Indeed, there's no sense in which you can convert between time zones with
Date
, as it's just a point in time.) (实际上,您无法使用
Date
在时区之间进行转换,因为它只是一个时间点。)
If you're concerned about the string representation, you can call toUTCString()
. 如果您担心字符串的表示形式,可以调用
toUTCString()
。 The toString()
function will always use the system local time. toString()
函数将始终使用系统本地时间。
For example, in a Chrome console: 例如,在Chrome控制台中:
> var now = new Date();
> now.toString()
"Thu Jun 12 2014 20:35:33 GMT+0100 (GMT Daylight Time)"
> now.toUTCString()
"Thu, 12 Jun 2014 19:35:33 GMT"
EDIT: Now we have a bit more information: 编辑:现在我们有更多的信息:
If you're going to do more work on the .NET side, you might want to look at my Noda Time project , too. 如果您打算在.NET方面做更多工作,那么您可能也想看看我的Noda Time项目 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.