This rule recommends using DateTimeOffset instead of DateTime for projects targeting .NET Framework 2.0 or later.
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.
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).
DateTime myDate = new DateTime(2008, 6, 19, 7, 0, 0, DateTimeKind.Local); // Noncompliant var now = DateTime.Now; // Noncompliant
DateTimeOffset myDate = new DateTimeOffset(2008, 6, 19, 7, 0, 0, TimeSpan.FromHours(-7)); // Compliant var now = DateTimeOffset.Now; // Compliant
Common DateTime pitfalls include:
DateTime of kind Local consider 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. DateTime of kind Unknown, calling ToUniversalTime() presumes the
DateTime.Kind is local and converts to UTC, if you call the method ToLocalTime(), it assumes the
DateTime.Kind is UTC and converts it to local. DateTimes objects, the user must ensure they are within the same time zone. DateTime doesn’t consider
UTC/Local when comparing; it only cares about the number of Ticks on the objects.