user3543512
user3543512

Reputation: 143

Converting datetime in C#

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.

Upvotes: 0

Views: 101

Answers (3)

Steve
Steve

Reputation: 216243

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.

Upvotes: 0

Ankur Gupta
Ankur Gupta

Reputation: 963

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.

Upvotes: 0

Mehmet Eren Yener
Mehmet Eren Yener

Reputation: 2036

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

here is what you need

Upvotes: 1

Related Questions