How to determine if values ​​are valid in DateTime?

We have a line of code:

DateTime.Now.AddMinutes(-1); 

which took place at 2 a.m. on the morning of March 29, 2015 in the UK. The return value was 1:59, however, due to daylight saving time, 1:59 actually did not occur and caused exceptions further down the line.

In my opinion, this is a bug in .NET, but instead of getting a fix for the framework, how can we verify that this is a valid DateTime before the following lines throw exceptions?

I am really looking for a row-wide extension method.

 if(!theDate.IsValidInTimezone(TimeZoneInfo.Local)) { // the time is not valid } 
+6
source share
2 answers

TimeZoneInfo.IsInvalidTime can help you here.

+6
source

This is not a mistake in itself. DateTime doesn't care about the actual offset, and if you do any arithmetic of time, you should use UTC.

Example:

  DateTime dt = new DateTime(2015, 3, 29, 2, 59, 0, DateTimeKind.Local); DateTime dt2 = dt.ToUniversalTime(); Console.WriteLine(dt.ToString()); Console.WriteLine(dt.AddMinutes(1).ToString()); Console.WriteLine(dt2.AddMinutes(1).ToLocalTime().ToString()); 

This will show the difference:

 29.3.2015 2:59:00 29.3.2015 3:00:00 29.3.2015 4:00:00 

Therefore, always indicate dates in UTC.

Or you can use DateTimeOffset , which remembers the actual offset. And you can convert to local time:

  DateTimeOffset dt = new DateTime(2015, 3, 29, 2, 59, 0, DateTimeKind.Local); Console.WriteLine(dt.ToString()); Console.WriteLine(dt.AddMinutes(1).ToString()); Console.WriteLine(dt.AddMinutes(1).ToLocalTime().ToString()); 

Results:

 29.3.2015 2:59:00 +02:00 29.3.2015 3:00:00 +02:00 29.3.2015 4:00:00 +03:00 
+2
source

Source: https://habr.com/ru/post/985122/


All Articles