All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S6566.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

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:

  • when working with 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.
  • when working with 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.
  • when comparing 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.

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy