Reputation: 14286
I have this method in the C# (server) side:
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. 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).
In the Javascript side:
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. 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)
. 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):
Upvotes: 0
Views: 1393
Reputation: 1500515
A Date
object doesn't have any concept of a time zone. It always represents a number of milliseconds since the Unix epoch.
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.)
If you're concerned about the string representation, you can call toUTCString()
. The toString()
function will always use the system local time.
For example, in a Chrome console:
> 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.
Upvotes: 3