The string was not recognized as a valid DateTime?

I try to convert a string to datetime , but every time I get:

The string was not recognized as a valid DateTime.

The code:

 string format = "dd/MM/yyyy"; obj.TransDate = DateTime.ParseExact(lbl_TransDate.Text.Split('/')[0] + "/" + lbl_TransDate.Text.Split('/')[1] + "/" + lbl_TransDate.Text.Split('/')[2], format, CultureInfo.InvariantCulture); 

When I debug the date I'm trying to execute, it is: 12/4/2012

+3
source share
4 answers

Format required

 string format = "dd/M/yyyy"; 

I don’t understand anything, why split the string into concatenation, so how do you get the same?

If the entrance is 12/4/2012, after splitting into '/', you will get 12, 4, 2012 and then join them back to get "12/4/2012". Why is this?

Also, if you really need this split, you can save it to an array, so you don't need to split it 3 times:

 var splits = lbl_TransDate.Text.Split('/'); DateTime.ParseExact(splits[0] + "/" + splits[1] + "/" + splits[2], ...); 

If you do not trust the input, the array of sections may not be long = 3, and moreover, you can use DateTime.TryParseExact

EDIT You can use overload with multiple formats. So if the input can be 12/4/2012 or 12/04/2012, you can provide both formats

 var formats = new[] {"dd/M/yyyy","dd/MM/yyyy"}; var date = DateTime.ParseExact("12/4/2012", formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal); 
+9
source

I agree with the other answers that it looks like you are doing a lot to solve what should be a simple problem. I would use the British date format from cultural information.

 var convertedDay = DateTime.Parse("12/04/2010", new CultureInfo("en-GB").DateTimeFormat); 
+2
source

You indicate MM when you have only one digit. Either use only one M , or a block with a zero value using the PadLeft function.

The following code demonstrates this with both dd and MM , complemented by the desired

 string format = "dd/MM/yyyy"; string mydate = "12/4/2012"; DateTime t = DateTime.ParseExact(mydate.Split('/')[0].PadLeft(2,'0') + "/" + mydate.Split('/')[1].PadLeft(2,'0') + "/" + mydate.Split('/')[2], format, CultureInfo.InvariantCulture); 

Output:

 12/04/2012 00:00:00 
+1
source

Make sure you add the following to your web configuration

 <system.web> <globalization culture="en-AU"/>... 

For the correct country code of the culture, see the following:

http://sharpertutorials.com/list-of-culture-codes/

+1
source

All Articles