Home > OS >  Date time format string C#
Date time format string C#

Time:09-22

I have problem to format string for correct date time parsing. I need to get variable of type "DateTime" from string.

For example, date is presented as a string "13-08-21/11:14:11". Correct date and time is: 13 of August 2021, time 11:14:11 AM.

Here is code that I use:

DateTime dateTime;
string strTime = "13-08-21/11:14:11";
string strFormat = @"dd-MM-YY'/'HH:mm:ss";

dateTime = DateTime.ParseExact(strTime, strFormat, CultureInfo.InvariantCulture);

I get error: System.FormatException: 'String was not recognized as a valid DateTime.' I try with different formating options but no results.

Can please someone help me to properly write format string? Thank you.

CodePudding user response:

Your format is a bit wrong.

DateTime dateTime;

string strFormat = @"dd-MM-y/HH:mm:ss";

//string strTime = "13-08-21/11:14:11"; // for date requested
string strTime = DateTime.Now.ToString(strFormat);  // for troubleshooting
Console.WriteLine("\nstrTime is: "   strTime);
dateTime = DateTime.ParseExact(strTime, strFormat, System.Globalization.CultureInfo.InvariantCulture);


If the above is not working, I would try troubleshooting. Rather than getting a datetime from a string, I would use your formatting string to convert Datetime.Now into a string. Then that string should be able to be converted back to a datetime with the formatting string.

If your ouput looks like:
strTime is: 20-09-YY/10:32:43 then it is probably the year segment that is wrong.

Here is more about the formatting: https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1

CodePudding user response:

To answer my question.

The first problem was a wrong format string.

And then there was an empty space at the end of my input string which I did not see at the beginning. Because of that parsing was not possible. Solution is to trim the end of string and now parsing works properly.

Thank you for help Mr. Lord and Mr. Morton.

  • Related