This rule recommends using DateTimeOffset instead of DateTime for projects targeting .NET Framework 2.0 or later.
Why is this an issue?
You should use DateTimeOffset instead of DateTime as it provides all the information that the DateTime
struct has, and additionally, the offset from Coordinated Universal Time (UTC). This way you can avoid potential problems created by the lack of
timezone awareness (see the "Pitfalls" section below for more information).
However, it’s important to note that although DateTimeOffset contains more information than DateTime by storing the
offset to UTC, it isn’t tied to a specific time zone. This information must be stored separately to have a full picture of the moment in time with the
use of TimeZoneInfo.
How to fix it
In most cases, you can directly replace DateTime with DateTimeOffset. When hardcoding dates with local kind, remember
that the offset is timezone dependent, so it should be set according to which timezone that data represents. For more information, refer to
DateTime and DateTimeOffset documentation from Microsoft (see the "Resources" section below).
Code examples
Noncompliant code example
Dim myDate As DateTime = New DateTime(2008, 6, 19, 7, 0, 0, DateTimeKind.Local) ' Noncompliant
Dim now = DateTime.Now ' Noncompliant
Compliant solution
Dim myDate As DateTimeOffset = New DateTimeOffset(2008, 6, 19, 7, 0, 0, TimeSpan.FromHours(-7)) ' Compliant
Dim now = DateTimeOffset.Now ' Compliant
Pitfalls
Common DateTime pitfalls include:
- when working with
DateTimeof kindLocalconsider the time offset of the machine where the program is running. Not storing the offset from UTC separately can result in meaningless data when retrieved from a different location. - when working with
DateTimeof kindUnknown, callingToUniversalTime()presumes theDateTime.Kindis local and converts to UTC, if you call the methodToLocalTime(), it assumes theDateTime.Kindis UTC and converts it to local. - when comparing
DateTimesobjects, the user must ensure they are within the same time zone.DateTimedoesn’t consider UTC/Local when comparing; it only cares about the number ofTickson the objects.