-2

I have changed format to dd-mm-yy in backend of page, i want to save date in'dd-mm-yy' format e.g.'23-02-2015' in database.and retreieve it in this format, i am using datetime picker in the text field...i changed the format of date picker to my 'dd-mm-yyyy' but its not saving data in that format and cause the below error

String was not recognized as a valid DateTime.

Any suggestions?

Farrukh Liaqat
  • 116
  • 1
  • 1
  • 11
  • 2
    Convert it back to default datetime format to store it in the DB: `yyyy-mm-dd` – juergen d Jun 14 '15 at 10:22
  • 1
    Better still, store it as a DateTime object in C# and only convert to a string in `dd-mm-yy` when displaying it to the user – Rhumborl Jun 14 '15 at 10:26
  • @ all the close voters: I disagree. the question is not unclear. it might be not up to standards of questions expected on SO, but the question itself (as the underling problem that's causing the error) is painfully clear (though could be avoided by googling the error message). – Zohar Peled Jun 14 '15 at 11:50

2 Answers2

3

Simply don't use strings to represent dates.
the DateTime struct of c# maps to sql server's datetime data type directly, meaning that you can simply send the DateTime struct as a parameter value in your SqlCommand object (I hope you are using parameterized queries or stored procedure. If not, then start using them right now, unless you want to be vulnerable to Sql injection attacks.)

Read here and there about the difference between Display format and storing format of date values in sql server.

Community
  • 1
  • 1
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
1

"String was not recognized as a valid DateTime."

First , why aren't you sending datetime object ?

If you can't(!) , well ,

If your datetime object id dt so do dt.ToString("yyyy-MM-ddTHH':'mm':'sszzz", DateTimeFormatInfo.InvariantInfo)

This will be a valid iso datetime string.

The only truly safe formats for date/time literals in SQL Server, at least for DATETIME and SMALLDATETIME, are:

YYYYMMDD
YYYY-MM-DDThh:nn[:ss[:mmm]]
Community
  • 1
  • 1
Royi Namir
  • 144,742
  • 138
  • 468
  • 792