What is the usage of the MySQL dateformat function?

The DATE_FORMAT function in MySQL is used to format date and time values in a specific format.
Syntax:
DATE_FORMAT(date, format)

Description of Parameters:

  1. Date: The date or time value to be formatted.
  2. format: the format of a specified date or time.

The commonly used formatting options are as follows:

  1. %Y: The year in four digits (e.g. 2021).
  2. %y: Year represented by 2 digits (e.g. 21).
  3. %m: Month (01-12).
  4. %d: Date (01-31).
  5. %H: Hour in 24-hour clock format (00-23).
  6. %H: The hour in 12-hour clock format (01-12).
  7. Minutes (00-59).
  8. %s: Seconds (00-59).
  9. %p: AM or PM.

I will meet you at the café at 3 o’clock.

I’ll see you at the café at 3.

  1. Format the date to the year-month-day format:
    SELECT DATE_FORMAT(‘2022-01-01’, ‘%Y-%m-%d’);
    Result: 2022-01-01
  2. Format the date in the form of month/day/year:
    SELECT DATE_FORMAT(‘2022-01-01’, ‘%m/%d/%Y’);
    Result: 01/01/2022
  3. Format the time into hours:minutes:seconds form in a 12-hour clock:
    SELECT DATE_FORMAT(‘2022-01-01 14:30:45’, ‘%h:%i:%s %p’);
    Result: 02:30:45 PM

Please be advised:

  1. The DATE_FORMAT function returns a string, not a date or time type.
  2. The DATE_FORMAT function can also be used for column names in queries, for example:
    SELECT DATE_FORMAT(column_name, format) FROM table_name;
    This will format the specified column in the query result.
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds