views:

2007

answers:

9

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

Thanks in advance.
Alan.

+12  A: 

The IFormatProvider argument can be null.

From the MSDN docs: "If provider is a null reference (Nothing in Visual Basic), the CultureInfo object that corresponds to the current culture is used."
John Sheehan
I realize I should not have implied that app.config needed to be used. You got at what I wanted -- 'just parse the date and don't bother me with stuff I don't care about'. Thanks.
AlanR
+3  A: 

Create an extension method:

public static DateTime ParseExactDateTime(this string dateString, string formatString) {
    return DateTime.ParseExact(dateString, formatString, new CultureInfo("en-CA", true));
}
John Sheehan
Thanks Will. I didn't really think that one through very well.
John Sheehan
+5  A: 

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.

David Sokol
+1  A: 

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

Jeff Hubbard
A: 

You could also use the Convert class

Convert.ToDateTime("2008/11/25");
Xian
+4  A: 

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

+2  A: 

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.

Scott Dorman
A: 

//Convert date to MySql compatible format

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

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

A: 

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

Nicholas H
Nothing, just dont' want to litter my code w/ it since Globalization isn't a concern in our shop.
AlanR