4

Can anyone explain the difference between the ToLocalTime() method and the LocalDateTime property in C# DateTimeOffset?

0

1 Answer 1

5

The docs state the following:

LocalDateTime:

Gets a DateTime value that represents the local date and time of the current DateTimeOffset object.

ToLocalTime():

Converts the current DateTimeOffset object to a DateTimeOffset object that represents the local time.

Looking at the code, we can see that the LocalDateTime property gets the value it represents as a UTC DateTime object and then converts it using the DateTime objects's ToLocalTime() method.

public DateTime UtcDateTime {
    [Pure]
    get {
        Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
        return DateTime.SpecifyKind(m_dateTime, DateTimeKind.Utc);
    }
}

public DateTime LocalDateTime {
    [Pure]
    get {
        Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
        return UtcDateTime.ToLocalTime();
    }
}

And we can see that .ToLocalTime() simply uses the same UtcDateTime property to retrieve the UTC DateTime object, again calls ToLocalTime() and then wraps it in a new DateTimeOffset object:

public DateTimeOffset ToLocalTime() {
    return ToLocalTime(false);
}

internal DateTimeOffset ToLocalTime(bool throwOnOverflow)
{
    return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow));
}

You can test the results with this code:

DateTimeOffset dto = new DateTimeOffset(2020, 10, 01, 9, 0, 0, 0, TimeSpan.FromHours(9));
Console.WriteLine(dto.ToString(System.Globalization.CultureInfo.InvariantCulture)); // 10/01/2020 09:00:00 +09:00

DateTime localTimeDt = dto.LocalDateTime;
Console.WriteLine(localTimeDt.ToString(System.Globalization.CultureInfo.InvariantCulture)); // 10/01/2020 02:00:00

DateTimeOffset localTimeDto = dto.ToLocalTime();
Console.WriteLine(localTimeDto.ToString(System.Globalization.CultureInfo.InvariantCulture)); // 10/01/2020 02:00:00 +02:00

Naturally, the DateTimeOffset retains the +2:00 of the system time of Rextester since that's the timezone it's based in.

Link to test

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.