MySQL Working With Dates
MySQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are trying to insert, matches the format of the date column in the database.
As long as your data contains only the date portion, your queries will work as expected. However, if a time portion is involved, it gets more complicated.
MySQL Date Data Types
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-
YEAR
- format YYYY or YY
Note: The date data type are set for a column when you create a new table in your database!
Working with Dates
Look at the following table:
Orders Table
OrderId | ProductName | OrderDate |
---|---|---|
1 | Geitost | 2008年11月11日 |
2 | Camembert Pierrot | 2008年11月09日 |
3 | Mozzarella di Giovanni | 2008年11月11日 |
4 | Mascarpone Fabioli | 2008年10月29日 |
Now we want to select the records with an OrderDate of "2008年11月11日" from the table above.
We use the following SELECT
statement:
The result-set will look like this:
OrderId | ProductName | OrderDate |
---|---|---|
1 | Geitost | 2008年11月11日 |
3 | Mozzarella di Giovanni | 2008年11月11日 |
Note: Two dates can easily be compared if there is no time component involved!
Now, assume that the "Orders" table looks like this (notice the added time-component in the "OrderDate" column):
OrderId | ProductName | OrderDate |
---|---|---|
1 | Geitost | 2008年11月11日 13:23:44 |
2 | Camembert Pierrot | 2008年11月09日 15:45:21 |
3 | Mozzarella di Giovanni | 2008年11月11日 11:12:01 |
4 | Mascarpone Fabioli | 2008年10月29日 14:56:59 |
If we use the same SELECT
statement as above:
we will get no result! This is because the query is looking only for dates with no time portion.
Tip: To keep your queries simple and easy to maintain, do not use time-components in your dates, unless you have to!