dhrm
dhrm

Reputation: 14934

How to convert DateTimeOffset to midnight in a specific time zone

Given a DateTimeOffset and a TimeZoneInfo, how can I convert that specific point in time instant to start of day in the given time zone?

Example:

public static DateTimeOffset AtMidnightInTimeZone(this DateTimeOffset date, TimeZoneInfo timeZone)
{
    return ?;
}

[Fact]
public void AtMidnightInTimeZone()
{
    // Arrange
    var dateTime = DateTimeOffset.Parse("2020-06-28T13:00:00+00:00");
    var timeZone = TZConvert.GetTimeZoneInfo("Europe/Paris");

    // Act
    var date = dateTime.AtMidnightInTimeZone(timeZone);

    // Assert
    Assert.Equal(DateTimeOffset.Parse("2020-06-28T00:00:00+02:00"), date);
}

Upvotes: 1

Views: 996

Answers (1)

Dilshod K
Dilshod K

Reputation: 3032

public static DateTimeOffset AtMidnightInTimeZone(DateTimeOffset date, TimeZoneInfo timeZone)
{
    var convertedDateTimeOffSet = TimeZoneInfo.ConvertTime(date, timeZone);
        var midNightTime = new DateTimeOffset(convertedDateTimeOffSet.Date, convertedDateTimeOffSet.Offset);
        return midNightTime;
}

Also see here: How to create a DateTimeOffset set to Midnight in Pacific Standard Time https://learn.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones

EDIT: This should work. It will convert the current DateTimeOffSet to given TimeZone and then using Offset property will get the Date of converted DateTimeOffSet which is midnight

Upvotes: 3

Related Questions