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.

2

3 Answers 3

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

here is what you need

Sign up to request clarification or add additional context in comments.

1 Comment

Is date a DateTime object?
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.