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

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

There is a newer version: 10.2.0.105762
Show newest version

When converting a string representation of a date and time to a DateTime object or any other temporal type with one of the available system parsing methods, you should always provide an IFormatProvider parameter.

Why is this an issue?

If you try to parse a string representation of a date or time without a format provider, the method will use the machine’s CultureInfo; if the given string does not follow it, you’ll have an object that does not match the string representation or an unexpected runtime error.

This rule raises an issue for the following date and time string representation parsing methods:

  • Parse
  • ParseExact
  • TryParse
  • TryParseExact

Of the following types:

  • System.DateOnly
  • System.DateTime
  • System.DateTimeOffset
  • System.TimeOnly
  • System.TimeSpan

How to fix it

Alway use an overload of the parse method, where you can provide an IFormatProvider parameter.

Code examples

Noncompliant code example

var dateTimeString = "4/12/2023 4:05:48 PM"; // This is an en-US format string - 12 of April 2023
var dateTimeObject = DateTime.Parse(dateTimeString); // This is wrongly parsed as 4th of December, when it's read in a machine with "CultureInfo.CurrentCulture" en-150 (English Europe)

var dateTimeString2 = "4/13/2023 4:05:48 PM"; // This is an en-US format string - 13 of April 2023
var dateTimeObject2 = DateTime.Parse(dateTimeString2); // Runtime Error, when it's parsed in a machine with "CultureInfo.CurrentCulture" en-150 (English Europe).

var timeInSaudiArabia = new TimeOnly(16, 23).ToString(new CultureInfo("ar-SA"));
var timeObject = TimeOnly.Parse(timeInSaudiArabia); // Runtime Error, when it's parsed in a machine with "CultureInfo.CurrentCulture" en-150 (English Europe).

Compliant solution

var dateTimeString = "4/12/2023 4:05:48 PM"; // This is an en-US format string - 12 of April 2023
var dateTimeObject = DateTime.Parse(dateTimeString, new CultureInfo("en-US"));

var dateTimeString2 = "4/13/2023 4:05:48 PM"; // This is an en-US format string - 13 of April 2023
var dateTimeObject2 = DateTime.Parse(dateTimeString2, new CultureInfo("en-US"))

var timeInSaudiArabia = new TimeOnly(16, 23).ToString(new CultureInfo("ar-SA"));
var timeObject = TimeOnly.Parse(timeInSaudiArabia, new CultureInfo("ar-SA"));

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy