Convert DateTime to Different TimeZone in C#, ASP.Net
There will be requirements where we need to display or convert the current date and time to a different time zone's data and time. We can do this by using TimeZoneInfo class packed in System.Collections.ObjectModel namespace.
The TimeZoneInfo class has method called ConvertTime() which can be used to convert a datetime to a specified time zone's datetime. TimeZoneInfo.ConvertTime(DateTime dt, TimeZoneInfo t) dt - DateTime that needs to be converted t - Target time zone The above function will return the converted DateTime.
The below code will print different time zones present in the server and the current time in each time zone by converting the server's current date time. Please note that this works only in .Netframework 3.5 and above.
protected void Page_Load(object sender, EventArgs e) { ReadOnlyCollection<TimeZoneInfo> tz = TimeZoneInfo.GetSystemTimeZones(); foreach (TimeZoneInfo t in tz) { Response.Write("Time Zone = "+t.DisplayName + " || Current DateTime = " + TimeZoneInfo.ConvertTime(DateTime.Now, t).ToString()); Response.Write("<br>"); } }
Include System.Collections.ObjectModel namespace for the above code to work.
|