Sunday, January 2, 2011

Dealing with DateTime different timezones

DateTime object gives us the luxury of only converting to and
from Universal Date Time (Formerly GMT) and Local Time (System Time Zone).

// expects DateTimeObject to contain Local Time and converts it to Universal
// Date Time value
DateTimeObject.ToUniversalTime()

// expects DateTimeObject to contain Universal Time and converts it to Local
// Date Time value
DateTimeObject.ToLocalTime()

So apparently there is no way to convert to and from a specific time zone.
But there are certain techinques to acheive what you need.

You can go along the following ways.


1) Use Javascript to pass the clients time zone offset to the server in a
hidden field and compute the British time on the server by first converting
the Server Local Time to Universal time and then adding the client's Time
Zone Offset to the Universal Time.

//javascript on client
dt = new Date();
locOffset = dt.getTimezoneOffset(); // get client's time zone offset
//Now pass this in a hidden feild to the server

//C# on Server
DateTime dt = DateTime.Now;
DateTime desiredTime = dt.ToUniversalTime().AddHours(offset);
//Note: offset is the client's time zone offset passed in the hidden field



2) If you want to perform all the computations on the server side then you
can probably use a class written by a gentleman which makes use of windows
APIs and can convert to any time zone.
http://staceyw.spaces.live.com/blog/cns!F4A38E96E598161E!931.entry

No comments:

Post a Comment