Saturday 2 February 2008

Comparing .NET Date on Server to Clients Date Anywhere in the World

I had to write a web application that will be hosted on US server with the date/time set to EST with daylight saving.

The application serves UK web clients, set to GMT with daylight saving, and I had to write javascript that would send the client time to the server and for the server to be able to compare it with it's own time.

I thought this would be difficult, but found this way to do it using UTC.

A little difficult to do because the base of the UTC date/time is different with .NET going for a base of 0001 AD and Javascript being from 1970. Also ticks in .net are measured in nanoseconds and javascript is measured in milliseconds.

Here is the javascript code:

var date = new Date();
var utcTicks = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());

That will get you the milliseconds in UTC (Universal Time) from 1970.

In .NET, C# here but you could do similar in VB.NET and will work for ASP.NET, WinForms etc...

DateTime now = DateTime.UtcNow;
DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0);
long ticks = (now - baseTime).Ticks / 10000;

Note you need to subtract the base time that javascript uses so the ticks start at 1970 and also divide by 10000, because the ticks will be in nano seconds and javascript are in milleseconds.

No comments: