1

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

Altaf Sami
  • 846
  • 5
  • 10
  • 21
  • 1
    possible duplicate of http://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy – Dhaval Marthak May 28 '13 at 17:22
  • 2
    By switching the "05" and the "28"? – Adam V May 28 '13 at 17:23
  • yes, date can be '12/31/2013 12:00:00' or any thing else with this format. – Altaf Sami May 28 '13 at 17:25
  • Think about what `.ParseExact` does in comparsion to `.Parse`: http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx ...as in, are you sure you want the 'exact' variety? – Arran May 28 '13 at 17:27
  • 1
    why don't you just add CONVERT(VARCHAR(10), [yourdate], 103) AS [DD/MM/YYYY] to your SQL ? It's the datetime format for dd/MM/yyyy. – RandomUs1r May 28 '13 at 17:30
  • yes i should try this. sorry i didn't think like this. i will do like this. – Altaf Sami May 28 '13 at 17:32
  • @AltafSami What is the database server and data type of your date column and how you read data? can you update the question with those information? – Damith May 28 '13 at 17:46

3 Answers3

6

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.

Damith
  • 62,401
  • 13
  • 102
  • 153
3

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");
Muhammad Raheel
  • 19,823
  • 7
  • 67
  • 103
ZZZ
  • 2,752
  • 2
  • 25
  • 37
  • This will fail because You have AM, PM in the given string – Damith May 28 '13 at 17:55
  • you are right. I did not check msdn for the standard date format token that take care of am/pm. The idea still stands: 2 steps. And depending on the quality or the diversification of the text data of date, you may design a structure to try a few date format string before giving up. – ZZZ May 29 '13 at 02:56
-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/

STA
  • 30,729
  • 8
  • 45
  • 59
Naveen
  • 1