I'm using the TimeZoneConverter NuGet package.
The Pacific standart time is use UTC-8
- Created a datetime as pacific timezone.
- The pacific time converted utc time.
- The utc time converted again to pacific timezone. But the result doesnt equal datetime in the first item. Why? Any idea?
[Fact]
public void DateTimeConvertTesting()
{
TimeZoneInfo pacificTimeZone = TZConvert.GetTimeZoneInfo("Pacific Standard Time"); // TimeZoneConverter
DateTimeOffset dateTimeOffsetPacific2 = new DateTimeOffset(2021, 09, 01, 11, 59, 0, pacificTimeZone.BaseUtcOffset);
DateTime utcDateTime = dateTimeOffsetPacific2.UtcDateTime;
DateTime pacificTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, pacificTimeZone);
Assert.True(dateTimeOffsetPacific2.DateTime == pacificTime);
}
CodePudding user response:
I think Caius Jard hits the correct issue on the comment.
Looks like for Pacific Standard Time on 2021, DST started March 14 02:00 AM and ends 7 November 02:00 AM.
TimeZoneInfo.ConvertTimeFromUtc
method handles the daylight saving itself. That means, if the Datetime
or DateTimeOffset
is a DST on Pacific Standard Time
, it returns the DST added value (which is 1 hour usually). That's why your pacificTime
variable
will be {9/1/2021 12:59:00 PM}
not {9/1/2021 11:59:00 PM}
If you have to use ConvertTimeFromUtc
for your test, it would be better to check first your DateTime
or DateTimeOffset
is a daylight saving time or not for that specific timezone. You can use TimeZoneInfo.IsDaylightSavingTime
method for that which have overloads both DateTime
and DateTimeOffset
.
var isDaylightSavingTime = pacificTimeZone.IsDaylightSavingTime(utcDateTime);
// for 2021, 09, 01, 11, 59, 0, this returns true.