3

How to correctly initialize DateTimeTimeZone from DateTimeOffset instance? Extensions class DateTimeTimeZoneExtensions has two variants of ToDateTimeTimeZone for DateTimeOffset.

public static DateTimeTimeZone ToDateTimeTimeZone(this DateTimeOffset dateTimeOffset)
{
    return new DateTimeTimeZone
    {
        DateTime = dateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture),
        TimeZone = string.Empty
    };
}

public static DateTimeTimeZone ToDateTimeTimeZone(this DateTimeOffset dateTimeOffset, TimeZoneInfo timeZoneInfo)
{
    return new DateTimeTimeZone
    {
        DateTime = dateTimeOffset.ToString(DateTimeFormat, CultureInfo.InvariantCulture),
        TimeZone = timeZoneInfo.Id
    };
}

Which one should i use? Why the first variant keep TimeZone field empty and doesn't calculate it from offset parameter of DateTimeOffset value?

What's point of TimeZone field in the second variant if dateTimeOffset.ToString() with DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffffffK" will already have correct time offset in result string because of K symbol in formatting string? The second variant is easiest way to have incorrectly initialized DateTimeTimeZone by putting wrong timeZoneInfo parameter. Because in this case you will have DateTime with offset of some time zone and TimeZone field with name for other time zone.

1 Answer 1

4

Why the first variant keep TimeZone field empty and doesn't calculate it from offset parameter of DateTimeOffset value?

It's not possible to extract a specific time zone based on offset information alone. There are 141 time zones, there are only 38 UTC-based time zone offsets, 27 if we exclude the 30 or 45 minute ones, this means that many time zones have the same offset. Not even considering the daylight savings time which further complicates the matter.

What's point of TimeZone field in the second variant if dateTimeOffset.ToString()[...]?

The API prioritizes TimeZone if it's specified. So the correct local time should be passed in dateTimeOffset parameter along with the timeZoneInfo. The offset passed in the dateTimeOffset parameter is 'ignored' in this case.

Which one should i use?

Generally speaking I would definitely use the latter, making sure to use the correct local time for the specified time zone.

The second variant is easiest way to have incorrectly initialized DateTimeTimeZone by putting wrong timeZoneInfo parameter

If you know the time zone, as you have to, to use the second option, it's easy to make sure the code passes the correct local time, I would consider passing mismatched time zone information a bug.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.