0
votes

How to change the date format in c#,i am retrieving the information from database,in database the date format its stored in "dd/mm/yyyy",but when i getting this date to my form,its showing error,the string is not a valid datetime format. for eg "2/13/2014" while i getting error when i retrieving this date,i have tried this code

 string orderd = row.Cells[1].Value.ToString();
                    DateTime dt = Convert.ToDateTime(lbl_date.Text);
                     DateTime orderdt = Convert.ToDateTime(orderd);

how to convert this date while retrieving.,

  string orderd = row.Cells[1].Value.ToString();
   DateTime orderdt = Convert.ToDateTime(orderd);

this code also grtting error,the row.cells[1].value is that i am getting the value from gridview,then i am converting into datetime.,but the showing "String was not recognized as a valid DateTime."

2
What is the column type in DB? Date? or varchar?Sriram Sakthivel
Try putting Convert.ToDateTime( [value here]);bolt19
Your code has - while the samples have - in.doctorlove
"2/13/2014" is "mm/dd/yyyy", not a "dd/mm/yyyy"ki11en
Note that if you've got a date or datetime field in the database, you shouldn't need to do any parsing at all.Jon Skeet

2 Answers

0
votes

If you have a date string in the format of dd/MM/yyyy then it's definitely not going to parse as yyyy-MM-dd so the error you see is correct.

I think what you are looking for is to parse the date in it's current format i.e.

DateTime orderdt = DateTime.ParseExact(orderd, "dd/MM/yyyy",
    System.Globalization.CultureInfo.InvariantCulture);

but display the date as yyyy-MM-dd

orderdt.ToString("yyyy-MM-dd")
0
votes

Have a look at MSDN. This documention includes many ways to format dates.

http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx