False positive:S6562 Provide the "DateTimeKind" when creating a date without time

Using DateTime constructor to create a date without time triggers false positive suggestion to supply DateTimeKind. By its nature, a date without time has no time, therefore has no zone, and therefore has no kind.

Microsoft understands that and rightfully does not allow to specify a kind on this construction signature. Sonar should take notice and omit warnings on this signature.

  • What language is this for? C#
  • Which rule? S6562
  • Why do you believe it’s a false-positive/false-negative?
  • Are you using SonarCloud? yes
    • SonarQube - which version?
    • SonarLint - which IDE/version?
      • in connected mode with SonarQube or SonarCloud?
  • How can we reproduce the problem?
new DateTime(year, month, day);

Hello @Ginkgo,

The example you provided can be a false positive in some cases and in some cases a true positive. It depends on the later usage of the created object.
If the created object is only used to represent a date through its life, it is a false positive. However, we are unable to track the usage of the object through its lifetime and that is why it can be a false positive.
On the other hand, if the object is later used with for example an AddHours call and after that converted to UTC or local time, the issue still exists and it can be considered as a true positive.

For the time being, we will leave it as is, until we gather further feedback on the rule, if the rule indeed creates a lot of noise (there are a lot of date-only usages), we will reconsider changing the implementation.

For your case, you have 3 options:

  • Mark it as a false positive if you only use the object for representing dates and you are on <NET5 dotnet version
  • Use DateOnly if you are >=NET6 dotnet version
  • If you use the object later for time representation, use a different overload of the constructor where you will be able to set the kind and set the time related arguments to 0

All the best,
Čaba

Thank you Čaba, that was very helpful