-2

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?

user5534263
  • 138
  • 12
  • 3
    If `actualValue` is a `DateTime`, the code you've got shouldn't even compile, and you wouldn't need to parse it. At the moment your question is very unclear. But basically, you shouldn't be reading the value as a string from the database to start with. – Jon Skeet Feb 04 '16 at 21:08
  • My apologies, it wasn't read from DB, its a string, as is. I have edited the question. – user5534263 Feb 04 '16 at 21:28
  • Even that doesn't fix the problem of your code not compiling if the type of actualValue is DateTime. – Jon Skeet Feb 04 '16 at 21:30

1 Answers1

2

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.

Glorin Oakenfoot
  • 2,455
  • 1
  • 17
  • 19
  • ok, I earlier tried M and d and it didn't work. but using hh instead of HH in addition to M and d worked. good catch on the 12 hr vs 24 hr format! – user5534263 Feb 04 '16 at 21:23