Tuesday, May 19, 2009

Adding a DateTime to a MySQL database

I wanted to add a datetime in an ASP.NET MVC application talking to a MySQL database.  I needed the date in the correct format in order to add it to the database.

This is one way to do it.

The data "cell" that will hold the datetime needs to be a 'DATE' type in MySQL.  Then, the user can set the Month, Day and Year needed.  (e.g. 1/2/2009).

This is the format I used, but you can modify it as according to your application.

So, when adding the date to your database, during your query :

table.datecell = STR_TO_DATE(' " + dateVariable + " ', '%m/%d/%y')

The format %m/%d/%y is month/day/year.  This will set the value of the cell to the date and with a time.

No comments:

Post a Comment