📅  最后修改于: 2023-12-03 14:44:26.801000             🧑  作者: Mango
MySQL is a popular open-source database management system that is widely used by programmers to store and manage data. One of the common requirements in programming is to store and manipulate dates. However, sometimes it is required to store only the date without any time information. In this article, we will discuss how to store and retrieve date without time in MySQL.
To store date without time in MySQL, we can use the DATE data type. The DATE data type stores only the date in YYYY-MM-DD format. We can create a table with the DATE data type for storing dates without time like below:
CREATE TABLE `my_table` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`date_col` DATE
);
In the above example, we have created a table with two columns. The first column is an auto-increment primary key, and the second column is of the DATE data type. We can insert date-only values into this table using the INSERT statement like below:
INSERT INTO `my_table` (`date_col`) VALUES ('2021-07-01');
To retrieve the date without time in MySQL, we can use the DATE_FORMAT function. The DATE_FORMAT function takes two arguments, the first argument is the date column we want to format, and the second argument is the format we want to apply. The format we need to apply is '%Y-%m-%d', which will return the date in YYYY-MM-DD format.
SELECT DATE_FORMAT(`date_col`, '%Y-%m-%d') AS `date` FROM `my_table`;
The above SQL statement will format the date_col
column in the my_table
table and return the date in YYYY-MM-DD format.
In this article, we discussed how to store and retrieve date without time in MySQL using the DATE data type and DATE_FORMAT function. By using these, we can manipulate and retrieve date-only values without any time information.