Edwin Sulaiman
Edwin Sulaiman

Reputation: 749

C# DateTimeOffset LocalDateTime vs ToLocalTime

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

Upvotes: 4

Views: 3166

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38850

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

Upvotes: 5

Related Questions