Tuesday, November 10, 2009

TimeZone Conversion in C#

hi.
.Net framework have some powerful classes for Date conversion.some time we need to convert date between different time Zones in code behind.In some cases difference in Time Zone leads difference in Date between locations.

To make this conversion .Net have very easy way.Just Provide leg/lead difference of hour/minute/seconds as argument in built in Function.

Suppose you want to convert Current date time to EST(GMT-5). this can be done by code.

DateTime currentDt = DateTime.Now.ToUniversalTime();//Current Converted to UTC
currentDt = DateTime.SpecifyKind(currentDt, DateTimeKind.Utc);//Say to runtime that this date is UTC date.

/*
we can convert between timezones with referance to UTC(GMT) time.
.Net Provides TimeZoneInfo class which provides Statis functions to make easy conversion between Time Zones.

Though It Takes many arguments ,Key point is ConvertTime method and TimeSpan
we can specify TimeSpan as diferance between GMT to EST,GMT to PST etc.
*/

lblGMT.Text = TimeZoneInfo.ConvertTime(currentDt, TimeZoneInfo.CreateCustomTimeZone("1", new TimeSpan(-5, 0, 0), "EST", "EST", "EDT", new TimeZoneInfo.AdjustmentRule[] { })).ToString();

you can read more about TimeZone and TimezoneInfo at

http://www.danrigsby.com/blog/index.php/2008/08/24/timezone-vs-timezoneinfo-in-net/

http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx

hope this will help you.

thanks.