views:

229

answers:

6

Hi,

My current code looks like this:

        DateTime dateBegin = DateTime.ParseExact(begin, "MM/dd/yyyy", null);
        DateTime dateEnd = DateTime.ParseExact(end, "MM/dd/yyyy", null);

But it throws an exception whenever the date in "end" is different. I get the dates from a DateTimePicker control, thus the date may look like "1/12/2010" and then it'll throw the exception. How do I avoid this?

Thanks.

+11  A: 

Is this winforms? just use .Value on the picker and you'll get the right DateTime - no need to parse.

Ultimately, "1/12/2010" isn't "MM/dd/yyyy"; you could also try ""M/d/yyyy" as a fallback?

string s = "1/12/2010";
string[] formats = { "MM/dd/yyyy", "M/d/yyyy", "M/dd/yyyy", "MM/d/yyyy" };
DateTime value = DateTime.ParseExact(s, formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
Marc Gravell
+4  A: 

Why don't you use DateTimePicker.Value?

winSharp93
A: 

If you provided the stack/exception information ti may be easier to help but I would expect it is throwing as the ParseExact is failing probably because it doesn't fit the format you are trying to narrow it too

Dean
+4  A: 

If you are getting the value from a DateTimePicker, why not use tha Value of that control which is already a DateTime? I'm not sure why you're trying to parse the string...

ZombieSheep
A: 

how about this ?

string begin = @"1/12/2010";
DateTime dateBegin = DateTime.ParseExact(begin, "M/dd/yyyy", null);

A good reference is

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

ala
And, to avoid the same problem with the day, use "M/d/yyyy", or even "M/d/y"
erikkallen
A: 

Cleared my cookies accidentally and now I can't add comments, damn.

@Marc

I didn't know that ParseExact could accept more than 1 string, that's what I needed. Thank you.

@winSharp93

I am, but afterwards I am saving the date to a file, and then reading it back into a string.

@ZombieSheep

See above.

@ala

This wouldn't work, because the date may differ, thus it can be "M/dd/yyyy" or "MM/dd/yyyy" but I didn't know that ParseExact accepts more than one string.

pancakelover