Priya Priya - 2 months ago 14
ASP.NET (C#) Question

Datetime format Issue: String was not recognized as a valid DateTime

I want to format the input string into MM/dd/yyyy hh:mm:ss format in C#.

The input string is in format

MM/dd/yyyy hh:mm:ss


For example :
"04/30/2013 23:00"


I tried
Convert.ToDateTime()
function, but it considers 4 as date and 3 as month which is not what I want. Actually month is 04 and date is 03.

I tried
DateTime.ParseExact()
function also, But getting Exception.

I am getting error:


String was not recognized as a valid DateTime.

Answer

Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify H instead of h if you are using 24 hour times:

DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)

See here for more information:

Custom Date and Time Format Strings

Comments