date format issue, String was not recognized as a

2020-07-29 16:00发布

问题:

I am getting dates from database and i want to convert the date in dd/MM/yyyy format,

I am trying this but it gives me error "String was not recognized as a valid DateTime."

DateTime pDate = DateTime.ParseExact("05/28/2013 12:00:00 AM", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Please let me know how i can convert into dd/MM/yyyy format?

Thanks

回答1:

2 steps:

DateTime pDate = DateTime.ParseExact("05/28/2013 12:00:00 AM", "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);


return pDate.ToString("dd/MM/yyyy");


回答2:

try with MM/dd/yyyy hh:mm:ss tt instead of dd/MM/yyyy

if you use DateTime.ParseExact The format of the string representation must match a specified format exactly or an exception is thrown.

if you need only the date

DateTime pDate = DateTime.ParseExact("05/28/2013 12:00:00 AM", "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
var dateOnly= pDate.ToString("dd/MM/yyyy");

As per your comment, database contain data with Type 'Date', So you can read it directly as DateTime. You can convert to string by calling ToString with the expected Format.



标签: c# asp.net