AlanR
AlanR

Reputation: 1172

Parsing exact dates in C# shouldn't force you to create an IFormatProvider

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));

Upvotes: 5

Views: 4344

Answers (9)

Nicholas Head
Nicholas Head

Reputation: 3726

What's wrong with using Globalization.CultureInfo.InvariantCulture ?

Upvotes: 0

Nkemjika
Nkemjika

Reputation:

//Convert date to MySql compatible format

DateTime DateValue = Convert.ToDateTime(datetimepicker.text);

string datevalue = DateValue.ToString("yyyy-MM-dd");

Upvotes: 0

Scott Dorman
Scott Dorman

Reputation: 42516

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.

Upvotes: 3

Joe
Joe

Reputation:

ParseExact needs a culture : consider "yyyy MMM dd". MMM will be a localized month name that uses the current culture.

Upvotes: 6

Xian
Xian

Reputation: 76601

You could also use the Convert class

Convert.ToDateTime("2008/11/25");

Upvotes: 1

John Sheehan
John Sheehan

Reputation: 78132

Create an extension method:

public static DateTime ParseExactDateTime(this string dateString, string formatString) {
    return DateTime.ParseExact(dateString, formatString, new CultureInfo("en-CA", true));
}

Upvotes: 3

Jeff Hubbard
Jeff Hubbard

Reputation: 9902

You could also simply create the IFormatProvider once and store it for later use.

Upvotes: 1

David J. Sokol
David J. Sokol

Reputation: 3566

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.

Upvotes: 5

s n
s n

Reputation:

The IFormatProvider argument can be null.

Upvotes: 14

Related Questions