Updated on 2024-08-19 GMT+08:00

date_format

This function is used to convert a date into a string based on the format specified by format.

Syntax

date_format(string date, string format)

Parameters

Table 1 Parameters

Parameter

Mandatory

Type

Description

date

Yes

DATE

or

STRING

Date to be converted

The following formats are supported:

  • yyyy-mm-dd
  • yyyy-mm-dd hh:mi:ss
  • yyyy-mm-dd hh:mi:ss.ff3

format

Yes

STRING

Format, based on which the date is converted

The value is a combination of the time unit (year, month, day, hour, minute, and second) and any character.

  • YYYY or yyyy indicates the year.
  • MM indicates the month.
  • dd indicates the day.
  • HH indicates the 24-hour clock.
  • hh indicates the 12-hour clock.
  • mi indicates the minute.
  • ss indicates the second.
  • SSS indicates the millisecond.

Return Values

The return value is of the STRING type.

  • If the value of date is not of the DATE or STRING type, the error message "data type mismatch" is displayed.
  • If the value of date is of the DATE or STRING type but is not in one of the supported formats, NULL is returned.
  • If the value of date is NULL, NULL is returned.
  • If the value of format is NULL, NULL is returned.

Example Code

Assume that the current time is 2023-08-14 16:59.

The value 2023-08-14 04:59:15.997 is returned.

select date_format(from_utc_timestamp(getdate(), 'UTC'),'yyyy-MM-dd hh:mm:ss.SSS');

The value 2023-08-14 is returned.

select date_format('2023-08-14','yyyy-MM-dd');

The value 2023-08 is returned.

select date_format('2023-08-14','yyyy-MM')

The value 20230814 is returned.

select date_format('2023-08-14','yyyyMMdd')