Create a Date Object from Day, Month, and Year Fields in MySQL
In a database schema with a 'date' table containing separate fields for 'day,' 'month,' and 'year,' it becomes necessary to create a date object for comparisons. This article outlines a solution for constructing a date object from these integer values.
Using the MAKEDATE() and DATE_ADD() functions, a DATETIME can be created from the year, month, and day components. MAKEDATE() generates a DATETIME representing the first day of the specified year. Subsequently, DATE_ADD() can be applied to add the month and day values.
For instance:
SELECT MAKEDATE(2013, 1); +-------------------+ | MAKEDATE(2013, 1) | +-------------------+ | 2013-01-01 | +-------------------+
To incorporate the month and day values:
SELECT DATE_ADD(MAKEDATE(2013, 1), INTERVAL (3)-1 MONTH); +---------------------------------------------------+ | DATE_ADD(MAKEDATE(2013, 1), INTERVAL (3)-1 MONTH) | +---------------------------------------------------+ | 2013-03-01 | +---------------------------------------------------+
Combining multiple DATE_ADD() calls allows for precise date construction:
SELECT DATE_ADD(DATE_ADD(MAKEDATE(2013, 1), INTERVAL (3)-1 MONTH), INTERVAL (11)-1 DAY); | DATE_ADD(DATE_ADD(MAKEDATE(2013, 1), INTERVAL (3)-1 MONTH), INTERVAL (11)-1 DAY) | +----------------------------------------------------------------------------------+ | 2013-03-11 | +----------------------------------------------------------------------------------+
To execute a date range query using this technique:
SELECT * FROM `date` WHERE DATE_ADD(DATE_ADD(MAKEDATE(year, 1), INTERVAL (month)-1 MONTH), INTERVAL (day)-1 DAY) BETWEEN '2013-01-01' AND '2014-01-01';
The above is the detailed content of How Can I Create a DATE Object in MySQL from Separate Day, Month, and Year Fields?. For more information, please follow other related articles on the PHP Chinese website!