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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Hardcoding the date and time format strings can lead to formats that consumers misunderstand. Also, if the same format is meant to be used in multiple places, it is easier to make a mistake when it’s hardcoded instead of using a format provided by an IFormatProvider or using one of the standard format strings.

What is the potential impact?

If a non-conventional format is used, the formatted date and time can be misunderstood. Also, if a mistake is made in the format, the formatted date can be incomplete. For example, you might switch the place of the minutes and month parts of a date or simply forget to print the year.

How to fix it

Instead of hardcoding the format, provide one from the available formats through an IFormatProvider or use one of the standard format strings.

Code examples

Noncompliant code example

void PrintTime()
{
    Console.WriteLine(DateTime.UtcNow.ToString("dd/MM/yyyy HH:mm:ss"));

    Console.WriteLine(DateTime.UtcNow.ToString("dd/mm/yyyy HH:MM:ss")); // Months and minutes have changed their places
}

Compliant solution

void PrintTime()
{
    Console.WriteLine(DateTime.UtcNow.ToString(CultureInfo.GetCultureInfo("es-MX")));

    Console.WriteLine(DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)); // Better provide a well known culture, so this kind of issues do not pop up
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy