Part 3.6SQL dates
MySQL provides several built-in functions for using dates. Whilst it is not the goal nor intention of this article in this tutorial to explain each of these, several of these functions have been explained on this page.
||Returns the current date and time|
||Returns the current date|
||Returns the current time|
||Extracts the date part of a date or date/time expression|
||Returns a single part of a date/time|
||Adds or subtracts a time to/from a date|
||Returns the number of days between two dates|
||Returns date/time data in different formats|
The information above was sourced from W3Schools.
Dates work in the same manner as selecting other forms of data in MySQL provided there is no time added to the date. Assuming the following table called 'orders' is used:
A simple SQL statement to find all purchases made on the 4th December 2005 would look like:
SELECT * FROM `orders` WHERE `date_purchased` = "2005-12-04"
The result would be:
However, when times are involved it becomes much harder. One such way of comparing whether something happens on a date when times are involved is to add times. For the following table:
To obtain all purchases made on the 4th of December 2005 it's easy enough to append some time and compare using the
SELECT * FROM `orders` WHERE `date_purchased` BETWEEN 2005-12-04 00:00:00 AND 2005-12-04 23:59:59
This way the results will be the same, since any date with a time between 00:00:00 and 23:59:59 is on the same day.