Home > Database > Mysql Tutorial > How to Correctly Convert C# DateTime to SQL's yyyy-MM-dd HH:mm:ss Format?

How to Correctly Convert C# DateTime to SQL's yyyy-MM-dd HH:mm:ss Format?

Patricia Arquette
Release: 2025-01-04 15:22:39
Original
1019 people have browsed it

How to Correctly Convert C# DateTime to SQL's yyyy-MM-dd HH:mm:ss Format?

Converting DateTime Format to SQL Format in C#

When saving date and time information to an SQL database using C#, it is necessary to convert it to the appropriate SQL format. For this, the format "yyyy-MM-dd HH:mm:ss" is widely used.

To address this need, consider the following code snippet:

DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
Copy after login

While this captures the date component accurately, the time component is always set to "12:00:00". To rectify this, try the improved code:

string sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd") + " " + myDateTime.TimeOfDay.ToString("HH:mm:ss");
Copy after login

However, this results in a compile-time error: "FormatException was unhandled". The issue stems from the attempt to call the Parse method on myDateTime, which is not a valid operation.

To resolve this, simply replace myDateTime.Parse.TimeOfDay with myDateTime.TimeOfDay in the code above. This corrects the method name and allows the time component to be formatted correctly.

Alternatively, to avoid these issues altogether, you can use the ToString method with a single format string, as shown below:

string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
Copy after login

This format includes the timestamp up to milliseconds, ensuring accurate representation in the SQL database.

The above is the detailed content of How to Correctly Convert C# DateTime to SQL's yyyy-MM-dd HH:mm:ss Format?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template