Convert the time according to the Timezone

Suresh.mekkattil
Posted by Suresh.mekkattil under ASP.NET category on | Points: 40 | Views : 4702
There are different issues when trying to convert the time from a Timezone to different.

ASP.NET 3.5 provides a class TimeZoneInfo which will be very helpful converting the time to a specific timezone.

Please see the code below:


// Specifing the culture
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");

// DateTime currentTime = new DateTime(2010, 01, 23, 10, 15, 00);
DateTime currentTime = DateTime.UtcNow;

/* System.TimeZone.CurrentTimeZone.GetUTCOffset(DateTime.Now).Hours */

/* string name = CultureInfo.GetCultureInfo("en-GB").DateTimeFormat; */

Console.WriteLine("UTC Time: " + TimeZoneInfo.ConvertTimeToUtc(DateTime.Today));
Console.ReadLine();

Console.WriteLine("Local Time: " + TimeZoneInfo.ConvertTimeFromUtc(currentTime, TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.StandardName)));
Console.ReadLine();

// Converting to utc
currentTime = TimeZoneInfo.ConvertTimeToUtc(currentTime);

Console.WriteLine("UTC Time: " + currentTime.ToString());
Console.Read();

Console.WriteLine("Time Zone Name: " + TimeZoneInfo.Local.StandardName);
Console.Read();

// Finding the current timezone
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.StandardName);

// Converting form the utc to the local time.
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(currentTime, timeZone);

Console.WriteLine("Local Time: " + currentTime.ToLocalTime());
Console.ReadLine();

Comments or Responses

Login to post response