Incorrect timezone from server side to Javascript

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):

  • It will get the time of the account time for different recorded footage (possibly in different locations).
  • There will be a timeline-like cursor which needs account time (not local time).
  • There will be options which will send the time back to the server side, so knowing the correct offset will make this easier.
Jon Skeet
people
quotationmark

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 need to display particular instants in time in a particular time zone, I suggest you do the conversion to text at the server side
  • If you need to send a local time back to the server, I suggest you do so in text
  • If you possibly can, I'd avoid having the idea of an "account time zone" anyway - try to store everything as UTC if possible. By all means render the values in a particular time zone, which the user should be able to control, but you should try to avoid doing any arithmetic using time zones.

If you're going to do more work on the .NET side, you might want to look at my Noda Time project, too.

people

See more on this question at Stackoverflow