Create rule S6588: Use UnixEpoch instead of creating DateTime instances that point to the unix epoch time (#1747)

This commit is contained in:
github-actions[bot] 2023-07-04 17:35:16 +02:00 committed by GitHub
parent 06dcb80993
commit 72c257b2c9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,2 @@
{
}

View File

@ -0,0 +1,29 @@
include::../why-dotnet.adoc[]
include::../impact-dotnet.adoc[]
include::../how-dotnet.adoc[]
=== Code examples
==== Noncompliant code example
[source,csharp,diff-id=1,diff-type=noncompliant]
----
void GetEpochTime()
{
var epochTime = new DateTime(1970, 1, 1);
}
----
==== Compliant solution
[source,csharp,diff-id=1,diff-type=compliant]
----
void GetEpochTime()
{
var epochTime = DateTime.UnixEpoch;
}
----
include::../resources-dotnet.adoc[]

View File

@ -0,0 +1,3 @@
== How to fix it
To fix this issue, use the `UnixEpoch` field of `DateTime` or `DateTimeOffset` instead of the constructor.

View File

@ -0,0 +1,3 @@
=== What is the potential impact?
You should not use the `DateTime` or `DateTimeOffset` constructors to set the time to the 1st of January 1970 to represent the beginning of the Unix epoch. Not everyone is familiar with what this particular date is representing and it can be misleading.

19
rules/S6588/metadata.json Normal file
View File

@ -0,0 +1,19 @@
{
"title": "Use the \"UnixEpoch\" field instead of creating \"DateTime\" instances that point to the beginning of the Unix epoch",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
],
"extra": {
},
"defaultSeverity": "Minor",
"ruleSpecification": "RSPEC-6588",
"sqKey": "S6588",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "targeted"
}

View File

@ -0,0 +1,6 @@
== Resources
=== Documentation
* https://learn.microsoft.com/en-us/dotnet/api/system.datetime.unixepoch[DateTime.UnixEpoch documentation]
* https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.unixepoch[DateTimeOffset.UnixEpoch documentation]
* https://en.wikipedia.org/wiki/Unix_time[Unix time]

View File

@ -0,0 +1,2 @@
{
}

View File

@ -0,0 +1,27 @@
include::../why-dotnet.adoc[]
include::../impact-dotnet.adoc[]
include::../how-dotnet.adoc[]
=== Code examples
==== Noncompliant code example
[source,vbnet,diff-id=1,diff-type=noncompliant]
----
Private Sub GetEpochTime()
Dim epochTime = New DateTime(1970, 1, 1)
End Sub
----
==== Compliant solution
[source,vbnet,diff-id=1,diff-type=compliant]
----
Private Sub GetEpochTime()
Dim epochTime = DateTime.UnixEpoch
End Sub
----
include::../resources-dotnet.adoc[]

View File

@ -0,0 +1,3 @@
== Why is this an issue?
With .NET Core the `UnixEpoch` field was introduced to `DateTime` and `DateTimeOffset` types. Using this field clearly states that the intention is to use the beginning of the Unix epoch.