org.sonar.plugins.csharp.S6562.html Maven / Gradle / Ivy
Why is this an issue?
Not knowing the Kind
of the DateTime
object that an application is using can lead to misunderstandings when displaying or
comparing them. Explicitly setting the Kind
property helps the application to stay consistent, and its maintainers understand what kind
of date is being managed. To achieve this, when instantiating a new DateTime
object you should always use a constructor overload that
allows you to define the Kind
property.
What is the potential impact?
Creating the DateTime
object without specifying the property Kind
will set it to the default value of
DateTimeKind.Unspecified
. In this case, calling the method ToUniversalTime
will assume that Kind
is
DateTimeKind.Local
and calling the method ToLocalTime
will assume that it’s DateTimeKind.Utc
. As a result, you
might have mismatched DateTime
objects in your application.
How to fix it
To fix this issue use a constructor overload that allows specifying the DateTimeKind
when creating the DateTime
object.
Code examples
Noncompliant code example
void CreateNewTime()
{
var birthDate = new DateTime(1994, 7, 5, 16, 23, 42);
}
Compliant solution
void CreateNewTime()
{
var birthDate = new DateTime(1994, 7, 5, 16, 23, 42, DateTimeKind.Utc);
}
Resources
Documentation