Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateTime for MySQL using C#

People also ask

How to use DateTime in MySQL?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

How can get date in dd mm yyyy format in MySQL?

MySQL DATE_FORMAT() Function The DATE_FORMAT() function formats a date as specified.

How to store date time in MySQL?

MySQL comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS.

How can create date and time table in MySQL?

In the MySQL documentation shows the following example: CREATE TABLE t1 ( ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP, dt DATETIME DEFAULT CURRENT_TIMESTAMP );


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


If your string format for the DateTime is fixed you can convert to the System.DateTime using:

string myDate = "12-Apr-1976 22:10";
DateTime dateValue = DateTime.Parse(myDate);

Now, when you need it in your specific format, you can then reverse the process, i.e.:

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

edit - updated code. For some strange reason DateTime.ParseExact wasnt playing nice.


I would strongly suggest you use parameterized queries instead of sending values as strings in the first place.

That way you only need to be able to convert your input format to DateTime or DateTimeOffset, and then you don't need to worry about the database format. This is not only simpler, but avoids SQL injection attacks (e.g. for string values) and is more robust in the face of database settings changes.

For the original conversion to a DateTime, I suggest you use DateTime.ParseExact or DateTime.TryParseExact to explicitly specify the expected format.


This works for me:

1.Extract date from oracle data base and pass it to variable

 string lDat_otp = "";

  if (rw_mat["dat_otp"].ToString().Length <= 0)
  {
      lDat_otp = "";
  }
  else
  {
      lDat_otp = rw_mat["dat_otp"].ToString();
  }

2.Conversion to mysql format

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

3.Pass formatForMySql variable to procedure or to something else