Search code examples
c#nodatime

Getting the current time in a timezone isn't taking into account daylight savings (I think)


I am trying to get the current times of a list of time zones using NodaTime. However, I'm having problems with the "EST" time zone. It's working great for getting the time in a number of other time zones as far as I can tell but "EST" doesn't seem correct.

Currently (as of right now) Google tells me EST is 18:40. Is there a way I can fix (for want of a better word) this so that I am able to get the local time of a given timezone based on the current UTC time?

void Main()
{
    var timeZones = new List<string>()
    {
        "Africa/Abidjan",
        "Africa/Bangui",
        "Africa/Casablanca",
        "Africa/Johannesburg",
        "America/Guayaquil",
        "America/New_York",
        "America/Vancouver",
        "America/Montreal",
        "Europe/Lisbon",
        "Europe/London",
        "EST"
    };

    GetLocalTimes(timeZones).Dump();
    //Africa/Abidjan 05/05/2019 22:40:22 
    //Africa/Bangui 05/05/2019 23:40:22 
    //Africa/Casablanca 05/05/2019 22:40:22 
    //Africa/Johannesburg 06/05/2019 00:40:22 
    //America/Guayaquil 05/05/2019 17:40:22 
    //America/New_York 05/05/2019 18:40:22 
    //America/Vancouver 05/05/2019 15:40:22 
    //America/Montreal 05/05/2019 18:40:22 
    //Europe/Lisbon 05/05/2019 23:40:22 
    //Europe/London 05/05/2019 23:40:22 
    //EST 05/05/2019 17:40:22 
}

public IReadOnlyDictionary<string, DateTime> GetLocalTimes(IEnumerable<string> timeZones)
{
    var dictionary = new Dictionary<string, DateTime>();

    foreach (var timeZone in timeZones)
    {
        var utcDateTime = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Utc);
        var zonedDateTime = Instant.FromDateTimeUtc(utcDateTime).InZone(DateTimeZoneProviders.Tzdb[timeZone]).ToDateTimeUnspecified();

        dictionary.Add(timeZone, zonedDateTime);
    }

    return dictionary;
}

Solution

  • This is not a NodaTime issue, it's a timezone confusion. EST does not change for daylight savings time. Those places that observe daylight savings time change to EDT which is the one hour difference. Bascially EST and EDT are two ways to track time in the Eastern Time Zone (ET).

    https://en.wikipedia.org/wiki/Eastern_Time_Zone

    Try using America/New_York instead.