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

DateTime myDate = new DateTime(2008, 6, 19, 7, 0, 0, DateTimeKind.Local); // Noncompliant

var now = DateTime.Now; // Noncompliant

Compliant solution

DateTimeOffset myDate = new DateTimeOffset(2008, 6, 19, 7, 0, 0, TimeSpan.FromHours(-7)); // Compliant

var now = DateTimeOffset.Now; // Compliant

Pitfalls

Common DateTime pitfalls include:

Resources

Documentation