How to use Standard Time Only in TimezoneInfo.ConvertTime C#

1.2k views Asked by At

I am having a Issue with the C# function of TimeZoneInfo.ConvertTime().

What i need to get is the Standard Time not the DST but i'm only getting DST is there a way to Tell the Function to only get the Result in Standard Time.

My local Timezone is UTC -6:00 Central America Standard Time, so if my time is 12:00 PM the Conversion i'm getting is throwing it at 2 PM Eastern Time but i need it to tell me it's 1:00 PM.

public static DateTime TimetoEst( DateTime timenow)
    {
        var currentTimeZone = TimeZone.CurrentTimeZone.GetUtcOffset(timenow).ToString();
        var estzone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
        var conver = TimeZoneInfo.ConvertTime(timenow, estzone);

        return conver;


    }

Thanks

1

There are 1 answers

0
Matt Johnson-Pint On BEST ANSWER

A couple of things:

  • The ID "Eastern Standard Time" represents both EST and EDT, with the appropriate transitions in place. It would more appropriately be called "Eastern Time", but alas this is the identifier and the convention used by Windows time zones.

  • The Eastern Time zone really does transition in and out of daylight saving time. If you were to always adjust to just Eastern Standard Time (UTC-5), you would be ignoring the reality of timekeeping in that region - that it is in Eastern Daylight Time (UTC-4) for dates in the summer months.

  • Your code will indeed return EST, but only for date values that are outside of the DST period.

Now, if you still think this is what you want to do - then you can do it without the TimeZoneInfo object at all. Simply adjust the result from the offset that applies to your source value, to the UTC-5 offset that applies to EST.

public static DateTime TimetoEst(DateTime timenow)
{
    var dto = new DateTimeOffset(timenow);  // will use .Kind to decide the offset
    var converted = dto.ToOffset(TimeSpan.FromHours(-5));
    return converted.DateTime;
}

This is what you asked, but for the record - I don't think this is the best plan. Besides the issues above - assuming that the input value should be interpreted based on the local time zone is not necessarily a good idea - and unless the input time has a .Kind of DateTimeKind.Utc, it will indeed use the computer's local time zone.

You did label the variable as timenow. If you are just after a DateTime which represents the current time in a fixed offset, then it's much safer just to get it like so:

DateTime dt = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(-5)).DateTime;

And if you really want the current time in the Eastern Time zone, taking DST into account when appropriate, then:

DateTime dt = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow,
                                                         "Eastern Standard Time");