Home >Database >Mysql Tutorial >How to Convert a DateTime Object in C# for MySQL?

How to Convert a DateTime Object in C# for MySQL?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 21:16:30353browse

How to Convert a DateTime Object in C# for MySQL?

Convert DateTime for MySQL in C#

In this post, we'll explore how to convert a DateTime object in C# to the specific format required by MySQL, which is "1976-04-09 22:10:00."

Problem:

Given a string containing a date value in a different format, we need to convert it to the MySQL-compatible format.

Solution:

There are multiple approaches to convert a DateTime object in C#:

  1. Hard-coding the ISO Format:
<code class="csharp">string dateValue = "12-Apr-1976 22:10";
string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm:ss");</code>
  1. Using CultureInfo.InvariantCulture:
<code class="csharp">CultureInfo isoDateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;
dateValue.ToString(isoDateTimeFormat.SortableDateTimePattern); // "1976-04-12T22:10:00"
dateValue.ToString(isoDateTimeFormat.UniversalSortableDateTimePattern); // "1976-04-12 22:10:00Z"</code>

These methods allow you to specify custom date and time formats or use predefined ISO formats that are compatible with MySQL.

The above is the detailed content of How to Convert a DateTime Object in C# for MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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