1

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);
}
dhrm
  • 14,335
  • 34
  • 117
  • 183
  • I would have suggested `date.Date` but that might be weird for an arbitrary time zone. Maybe `var x = date.ToOffset(timeZone); return x - x.TimeOfDay;`? – Jeremy Lakeman Oct 01 '21 at 06:34

1 Answers1

3
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

Dilshod K
  • 2,924
  • 1
  • 13
  • 46
  • Are you sure that works if the original date is not UTC or the machine local timezone? Since date.Date will give an unspecified kind, which `new DateTimeOffset` would assume is local? – Jeremy Lakeman Oct 01 '21 at 06:41
  • I'm not sure that works for all cases. If the input is UTC e.g. "2020-06-28T23:00:00+00:00" and time zone "Europe/Paris", that would return midnight of 28th instead of the expected 29th. – dhrm Oct 01 '21 at 06:56