I have a DateTime object
DateTime dtt = new DateTime(2012, 6, 18, 12, 0, 0)
I am converting it to string this way
string str = dtt.ToString("yyyyMMddtt");
I get str as “20120618PM”
Fine till here
But when I try to convert this back to DateTime using DateTime.ParseExact() i get an error
String was not recognised a valid DateTime
dtt = DateTime.ParseExact(str, "yyyyMMddtt", null);
I even tried providing culture but I still get an error
dtt = DateTime.ParseExact(str, "yyyyMMddtt", CultureInfo.InvariantCulture);
What is wrong here which i am missing?
According to the documentation for the DateTime.ParseExact method you will get a
FormatExceptionin the following case.You don’t have an hour component at all and there cannot be any agreement leading to the exception.
If you really want to stick with the format
yyyyMMddttyou will have to perform your own parsing of the AM/PM part and based on that modify the time part of theDateTime. You can then parse the remainder of the date usingyyyyMMdd.