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.

Posted on

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

  1. 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.

  2. 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.

  3. Use DATE() to compare dates:

    SELECT * FROM appointments WHERE DATE(appt_time) = '2023-01-05';
    

    This selects appoinments on a specific date.

  4. 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.

  5. 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 time
  • YEAR() - Extract year
  • MONTH() - Extract month
  • DAY() - Extract day

So DATE() provides a simple way to get the date part from datetimes in MySQL.