Last Updated: February 25, 2016
·
562
· rarous

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.