How to Convert DateTime Objects for MySQL in C#
MySQL databases have a specific date and time format that differs from the default formatting in C#. To facilitate data exchange, converting DateTime objects to MySQL's preferred format is necessary.
Converting Using ISO Format
To hard-code the ISO format for conversion:
<code class="csharp">string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm:ss");</code>
Converting Using Culture-Specific Formatting
To use culture-specific formatting:
<code class="csharp">var isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat; // For format "1976-04-12T22:10:00" dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern); // For format "1976-04-12 22:10:00Z" dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern);</code>
Converting Using dd mm hh yy Method
Although not recommended, the "dd mm hh yy" method can be used as follows:
<code class="csharp">int day = int.Parse(str.Substring(0, 2)); int month = int.Parse(str.Substring(3, 2)); int year = int.Parse(str.Substring(6, 2)); int hour = int.Parse(str.Substring(9, 2)); int minute = int.Parse(str.Substring(12, 2)); DateTime convertedDate = new DateTime(year, month, day, hour, minute, 0);</code>
Note:
The above is the detailed content of How to Convert DateTime Objects for MySQL in C#?. For more information, please follow other related articles on the PHP Chinese website!