I have a string like below
1/1/1970 12:00:00 AM
I want it in the yyyy-MM-dd format (in this case 1970-01-01) My parsing code is
var actualDate = DateTime.ParseExact(actualValue,"MM/dd/yyyy HH:mm:ss tt",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
But I keep getting the error, that the string is not recognized as a valid date time. I looked at my variable actualValue and it is of type DateTime, so am thinking that the problem is with the format MM/dd/yyyy HH:mm:ss tt ,What is wrong with this?
First, you shouldn't be storing or fetching dates as text in the DB.
To your specific issue, however, MM
and dd
are the two-digit variety of month and day. Obviously your date text doesn't use the two-digit-only variety, so use M
and d
. Also, HH
is on a 24-hour clock. Using tt
, which is AM/PM, would imply not having a 24 hour clock, so you would want to use hh
instead.
For more, look at MSDN for custom date/time formatting.