Convert DateTime for MySQL using C#
Question:
How can you convert a DateTime object in C# to a format accepted by a MySQL database, specifically the '1976-04-09 22:10:00' format?
Answer:
There are several ways to convert a DateTime object for MySQL in C#.
Using the ISO 8601 Format:
You can use the ToString method with the appropriate format string to convert the DateTime object to the ISO 8601 format, which is accepted by MySQL. For instance:
<code class="c#">string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm:ss");</code>
This will result in a string in the format "1976-04-12 22:10:00".
Using the Universal Sortable DateTime Format:
You can also use the UniversalSortableDateTimePattern property of the DateTimeFormat class to convert the DateTime object to the Universal Sortable DateTime Format, which is also accepted by MySQL. For example:
<code class="c#">// Just to shorten the code var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat; // "1976-04-12T22:10:00" dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern); // "1976-04-12 22:10:00Z" dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern)</code>
Using a Custom Format:
You can also use a custom format string to convert the DateTime object to a specific format. For instance, to convert the DateTime object to the "12-Apr-1976 22:10" format, you can use the following format string:
<code class="c#">string customFormat = "dd-MMM-yyyy HH:mm"; dateValue.ToString(customFormat);</code>
The above is the detailed content of How to Convert a C# DateTime Object to a MySQL-Compatible Format?. For more information, please follow other related articles on the PHP Chinese website!