Search code examples
c#stringdatetimeuwp

String 'yyyy-mm-dd HH:mm:ss' was not recognized as a valid DateTime


I have a string like below:

string expiredDate = "2026-05-24 18:54:55";

I want to convert it to DateTime format using the code below:

DateTime myDate = DateTime.ParseExact(expiredDate, "dd MMMM yyyy HH:mm:ss", CultureInfo.InvariantCulture);

But it didn't work and I get this error:

error message

I've also tried replacing it using

DateTime expiredDate = DateTime.ParseExact(expiredDate, "dd MMMM yyyy HH:mm:ss", CultureInfo.CreateSpecificCulture("id-id"));

but I still get the same error.

How to solve it?


Solution

  • As mentioned already you input date string does not match with the format provided in the parse exact method. To convert the string to DateTime you can do the following:

    DateTime myDate = DateTime.ParseExact(expiredDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
    

    If you want to re-convert the DateTime object to string with your format you can then convert it to string as f

    string myDateStr = myDate.ToString("dd MMMM yyyy HH:mm:ss");