Sunday, December 22, 2024

MySQL TIME_FORMAT() Function

 The TIME_FORMAT() function in MySQL is used to format a time value according to a specified format string. It takes a time expression (such as a column or a time literal) and formats it as per the provided format.

Syntax:

TIME_FORMAT(time, format)
  • time: The time value that you want to format.
  • format: A string that specifies the desired format. The format string can contain various format specifiers.

Format Specifiers:

  • %H: Hour (00 to 23)
  • %i: Minutes (00 to 59)
  • %s: Seconds (00 to 59)
  • %p: AM or PM
  • %r: Time in 12-hour AM/PM format (hh:mm:ss AM/PM)
  • %T: Time in 24-hour format (hh:mm:ss)

Example Usage:

  1. Format Time in 24-Hour Format:
SELECT TIME_FORMAT('15:45:30', '%H:%i:%s') AS formatted_time;

Result: 15:45:30

  1. Format Time in 12-Hour Format:
SELECT TIME_FORMAT('15:45:30', '%h:%i:%s %p') AS formatted_time;

Result: 03:45:30 PM

  1. Using a Column with TIME_FORMAT:
SELECT TIME_FORMAT(time_column, '%h:%i:%s %p') AS formatted_time
FROM your_table;

This will format the values from time_column in the 12-hour format with AM/PM.

The TIME_FORMAT() function is particularly useful when you need to display time values in a specific format, either in reports, interfaces, or in results returned from queries.

No comments:

Post a Comment