MySQL DATE() 用法与实例
The DATE() function in MySQL is used to extract the date part from a datetime expression. It returns the date in ‘YYYY-MM-DD’ format.
The DATE() function in MySQL is used to extract the date part from a datetime expression. It returns the date in ‘YYYY-MM-DD’ format.
Syntax
The syntax for DATE() is:
DATE(datetime)
Where datetime is a datetime value or expression.
Examples
-
Get the date part from a datetime:
SELECT DATE('2023-01-14 09:15:30');This returns ‘2023-01-14’, extracting just the date part.
-
Get date from a timestamp column:
SELECT DATE(created_at) FROM posts;This returns just the date from the timestamp in the created_at column.
-
Use
DATE()to compare dates:SELECT * FROM appointments WHERE DATE(appt_time) = '2023-01-05';This selects appoinments on a specific date.
-
Use
DATE()in a WHERE clause:SELECT * FROM sales WHERE DATE(transaction_time) BETWEEN '2023-01-01' AND '2023-01-31';This returns sales for January 2023.
-
Get the current date without time:
SELECT DATE(NOW());This returns the current date by extracting it from the NOW() datetime.
Other Similar Functions
TIME()- Extract timeYEAR()- Extract yearMONTH()- Extract monthDAY()- Extract day
So DATE() provides a simple way to get the date part from datetimes in MySQL.