Getting the Server-Side Offset to the JavaScript Epoch in C#

3. September 2009 16:50

Just in case anyone else needs it, here's my method for getting the millisecond offset of a server's local time to UTC time in milliseconds, for use in client-side JavaScript.

private int ServerSideJsUtcOffset
    get {
        DateTime epoch = new DateTime(1970,1,1);
        int offset = (int)epoch.ToUniversalTime().Subtract(epoch).TotalMilliseconds;
        return offset;

There's really not much to it, it's mainly so that I can handle converting serialized dates to a proper local time on the client. The DateTime objects in question are stored in a database as the UTC date-time, via an ORM tool, and sent to the client with System.Web.Script.Serialization.JavaScriptSerializer. All the server-side code uses the same ORM tool, and all the client-side JSON is processed via the same local parser. So it was simply easier adjusting the client-side parser than it was to adjust the server-side class hierarchy.

I should note that I could have set the initial date to DateTime.Now instead of implicitely using the JS epoch, as the difference would be the same for any localized DateTime, just felt the clarity was worth it.

Comments are closed


Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.