YosiFZ
YosiFZ

Reputation: 7900

String To DateTime Exception

I have this String :

05/09/2013 23:23

And i want to convert it to DateTime with this:

DateTime alarmDateTime = new DateTime();
alarmDateTime = DateTime.ParseExact(date, "MM/dd/YYYY HH:mm", null);

And i get this Exception:

String was not recognized as a valid DateTime.

Any idea why it happens?

Upvotes: 1

Views: 110

Answers (3)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

If date seperator in your system is "/" then just changing YYYY to yyyy will work.

If it is not then use this

 string date = "05/09/2013 23:23";

 DateTime alarmDateTime = new DateTime();
 alarmDateTime = DateTime.ParseExact(date, "MM/dd/yyyy HH:mm", 
                                     CultureInfo.InvariantCulture);

enter image description here

Upvotes: 1

Roee Gavirel
Roee Gavirel

Reputation: 19443

DateTime alarmDateTime = DateTime.ParseExact(date, "MM/dd/yyyy HH:mm", null);

Upvotes: 1

gareththegeek
gareththegeek

Reputation: 2418

I think the year should be lower case 'y'. There is also no need to instantiate the date time on the first line as the value is overwritten on the second.

Upvotes: 7

Related Questions