Home > Database > Mysql Tutorial > How Can I Create a DATE Object in MySQL from Separate Day, Month, and Year Fields?

How Can I Create a DATE Object in MySQL from Separate Day, Month, and Year Fields?

Linda Hamilton
Release: 2024-12-23 04:57:37
Original
372 people have browsed it

How Can I Create a DATE Object in MySQL from Separate Day, Month, and Year Fields?

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        |
+-------------------+
Copy after login

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                                        |
+---------------------------------------------------+
Copy after login

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                                                                       |
+----------------------------------------------------------------------------------+
Copy after login

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';
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template