Altaf Sami
Altaf Sami

Reputation: 846

date format issue, String was not recognized as a valid DateTime

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

Upvotes: 1

Views: 17582

Answers (3)

Naveen
Naveen

Reputation: 1

DateTime d = DateTime.Parse( 
   "15/12/2019",
   new System.Globalization.CultureInfo("pt-BR"));

refer https://blog.submain.com/string-was-not-recognized-as-valid-datetime/

Upvotes: -1

ZZZ
ZZZ

Reputation: 2812

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");

Upvotes: 3

Damith
Damith

Reputation: 63105

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.

Upvotes: 6

Related Questions