Monday, June 3, 2013

Parsing string to C# DateTime from specific time zone into UTC

If you need to parse a string representation of a DateTime into a specific time zone, use the DateTimeOffset in C# to assist.  For example, assume your code is executing in PST and you have a string like "1/6/2013 11:00:21 AM" that represents a time in EST.  How to do you convert this into UTC format?

Use the TimeZoneInfo.BaseUtcOffset member to create a DateTimeOffset structure.  Using this structure, you can then easily convert to UTC by by calling DateTimeOffset.UtcDateTime.


private void CalculateTimeToEastern()
{
  DateTime utc = ParseToTimeZone("1/6/2013 11:00:21 AM", "Eastern Standard Time").UtcDateTime;
}

private DateTimeOffset ParseToTimeZone(string s, string timeZoneName)
{
  TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName);
  DateTimeOffset offset = new DateTimeOffset(DateTime.Parse(s), easternZone.BaseUtcOffset);

  return offset;
}

Note from MSDN (which is interesting)
These uses for DateTimeOffset values are much more common than those for DateTime values. As a result, DateTimeOffset should be considered the default date and time type for application development.

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...