Search code examples
c#.netdatetimetimezoneportable-class-library

Convert Eastern Standard Time String to UTC DateTime using Portable Class Library


I have a string which I know is Eastern Standard Time:

"8/14/2013 5:51am"

I want to convert this to a UTC DateTime in my portable class library, taking daylight savings time into consideration. I have discovered that Portable Class Library does not have the following method:

TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")

Is this possible to do in a Portable Class Library? If not, how do I do it in a normal class library given that there is no time zone information in the string?


Solution

  • TimeZoneInfo is not fully portable. It exists, but has no data to back it up, so it can only provide access to UTC and the local time zone. It can't resolve a zone by its id.

    Fortunately, Noda Time has a portable version, but you will need to use the IANA zone name, not the Windows zone name. See the timezone tag wiki for more details. Also make sure you read about limitations of NodaTime as a PCL.

    using NodaTime;
    using NodaTime.Text;
    
    LocalDateTimePattern pattern = LocalDateTimePattern
                                     .CreateWithInvariantCulture("M/dd/yyyy h:mmtt");
    LocalDateTime ldt = pattern.Parse("8/14/2013 5:51am").Value;
    
    DateTimeZone tz = DateTimeZoneProviders.Tzdb["America/New_York"];
    ZonedDateTime zdt = tz.AtLeniently(ldt);
    Instant instant = zdt.ToInstant();
    
    Debug.WriteLine(instant.ToString());  // 2013-08-14T09:51:00Z   (UTC)
    
    // if you need it as a DateTime
    DateTime utc = instant.ToDateTimeUtc();