Convert DateTime for MySQL using C#

Steven Spielberg picture Steven Spielberg · Sep 3, 2010 · Viewed 102.3k times · Source

I want to change the DateTime for MySQL in C#.

My MySQL database only accept this format 1976-04-09 22:10:00.

In C# have a string who have a date value:

string str = "12-Apr-1976 22:10";

I want to convert for MySQL then it look like:

1976-04-12 22:10

How I can change them or how other programmer do this by using dd mm hh yy method? Can anyone tell me about them?

Answer

abatishchev picture abatishchev · Sep 3, 2010

Keep in mind that you can hard-code ISO format

string formatForMySql = dateValue.ToString("yyyy-MM-dd HH:mm:ss");

or use next:

// 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)

and so on