date format issue, String was not recognized as a

2020-07-29 15:54发布

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

标签: c# asp.net
2条回答
在下西门庆
2楼-- · 2020-07-29 16:09

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.

查看更多
We Are One
3楼-- · 2020-07-29 16:11

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");
查看更多
登录 后发表回答