Parsing exact dates in C# shouldn't force you to create an IFormatProvider
-
09-06-2019 - |
Question
Someone please correct me if I'm wrong, but parsing a yyyy/MM/dd (or other specific formats) dates in C# should be as easy as
DateTime.ParseExact(theDate, "yyyy/MM/dd");
but no, C# forces you to create an IFormatProvider.
Is there an app.config friendly way of setting this so I don't need to do this each time?
DateTime.ParseExact(theDate, "yyyy/MM/dd", new CultureInfo("en-CA", true));
Solution
The IFormatProvider argument can be null.
OTHER TIPS
ParseExact needs a culture : consider "yyyy MMM dd". MMM will be a localized month name that uses the current culture.
Use the current application culture:
DateTime.ParseExact("2008/12/05", "yyyy/MM/dd", System.Globalization.CultureInfo.CurrentCulture);
You can set the application culture in the app.config using the Globalization tag. I think.
Create an extension method:
public static DateTime ParseExactDateTime(this string dateString, string formatString) {
return DateTime.ParseExact(dateString, formatString, new CultureInfo("en-CA", true));
}
It requires the format provider in order to determine the particular date and time symbols and strings (such as names of the days of the week in a particular language). You can use a null, in which case the CultureInfo object that corresponds to the current culture is used.
If you don't want to have to specify it each time, create an extension method which either passes null or CultureInfo("en-CA", true) as the format provider.
You could also simply create the IFormatProvider once and store it for later use.
You could also use the Convert class
Convert.ToDateTime("2008/11/25");
//Convert date to MySql compatible format
DateTime DateValue = Convert.ToDateTime(datetimepicker.text);
string datevalue = DateValue.ToString("yyyy-MM-dd");
What's wrong with using Globalization.CultureInfo.InvariantCulture ?