Local times for custom time zone
Working with Time across many time zones is sometimes painful. Best practice in .net is to use build in type DateTimeOffset
that contains time zone information. If your application uses just plain old DateTime
you have harder time.
I hope that your application is working with UTC values. You work with UTC values everywhere but UI. For UI purposes we have to write little helper extension method. This method extends DateTime
and converts it from UTC to given Time zone.
public static DateTime ToLocalTime(this DateTime utcDate, string timeZoneId) {
var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
var utc = new DateTimeOffset(DateTime.SpecifyKind(utcDate, DateTimeKind.Utc));
return utc.ToOffset(timeZone.GetUtcOffset(utcDate)).DateTime;
}
The timeZoneId
is a value of TimeZoneInfo.Id property.
Written by Aleš Roubíček
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Csharp
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#