Home >Database >Mysql Tutorial >How to Convert a C# DateTime Object to SQL's yyyy-MM-dd HH:mm:ss Format?
Converting DateTime to SQL Format in C#
In order to store timestamps in the SQL format from .NET's DateTime datatype, you need to convert it to the "yyyy-MM-dd HH:mm:ss" format.
Your initial approach involved separating the date and time components, but it resulted in an incorrect time value ("12:00:00"). To address this, try the following:
DateTime myDateTime = DateTime.Now; string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
The syntax ToString("yyyy-MM-dd HH:mm:ss.fff") directly formats the DateTime object into the required SQL format, including the fractional seconds (.fff). This is a more accurate representation of the timestamp.
Remember that Parse and TryParse are used to convert strings to DateTime objects, not vice versa. They are not applicable in this case.
By utilizing the ToString method with the appropriate format string, you can seamlessly convert the DateTime value into the SQL-compliant format for storage or retrieval.
The above is the detailed content of How to Convert a C# DateTime Object to SQL's yyyy-MM-dd HH:mm:ss Format?. For more information, please follow other related articles on the PHP Chinese website!