0

I have a datetime format as "20/6/2014 12:45:00 PM" and I wish to convert it to my SQL datetime format eg: "2013-06-01 12:38:28.000"

DateTime date = DateTime.ParseExact("20/6/2014 12:45:00 PM", "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);

Tried the above but it doesn't work. Error - String not recognized as a valid datetime.

user3543512
  • 133
  • 1
  • 1
  • 13
  • possible duplicate of [Given a DateTime object, how do I get a ISO 8601 date in string format?](http://stackoverflow.com/questions/114983/given-a-datetime-object-how-do-i-get-a-iso-8601-date-in-string-format) – Tanner Jun 30 '14 at 08:18
  • The original value is a string or it is already a datetime? – Steve Jun 30 '14 at 08:19

3 Answers3

1
string MysqlDateFormat = date.ToString("yyyy-MM-dd HH:mm:ss");

here is what you need

Mehmet Eren Yener
  • 2,006
  • 1
  • 23
  • 37
0
string date=System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

use this it will return you current date and time and convert it according to your format.

Ankur Gupta
  • 933
  • 3
  • 15
  • 27
0

It doesn't work because you use a string format that is not valid for the string

"20/6/2014 12:45:00 PM"

For this kind of string you need a format mask like

"dd/M/yyyy hh:mm:ss tt"

However it is not very clear if you have an input date stored in a string and you want to transform it to a valid DateTime variable or, instead, you have a valid DateTime variable and want a string representing a date formatted in a specif manner.

For the first case

string validDate = "20/6/2014 12:45:00 PM";
DateTime t = DateTime.ParseExact(validDate, "dd/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

For the second case

DateTime d = new DateTime(2014, 6, 20, 12, 45, 0);
string validDate = d.ToString("yyyy-MM-dd h:mm:ss.fff");

Notice however, that if you want to use this value to set a field in your database through an INSERT/UPDATE query you shouldn't pass strings, but use a parameterized query passing a parameter of the correct datatype.

Steve
  • 213,761
  • 22
  • 232
  • 286