What is the usage of from_unixtime in MySQL?
The function from_unixtime in MySQL is used to convert Unix timestamp into the corresponding date and time format.
Its syntax is as follows:
FROM_UNIXTIME(unix_timestamp [, format])
In which, unix_timestamp is an integer that represents the number of seconds from 00:00:00 UTC on January 1, 1970 to the specified time. Format is an optional parameter used to specify the output date and time format.
Here are some common examples of date and time formats:
- %Y-%m-%d: Output in the format of “year-month-day”, for example: 2022-01-01
- Output in the format of “year-month-day hour:minute:second”, for example: 2022-01-01 10:30:00.
- Date: Output in the “year-month-day” format, for example: 2022-01-01
Example usage:
- Convert a Unix timestamp to the default date and time format.
SELECT FROM_UNIXTIME(1641024000);
Output: January 1, 2022 12:00:00 AM
- Convert Unix timestamp to a specified date format.
SELECT FROM_UNIXTIME(1641024000, '%Y-%m-%d');
Output: January 1, 2022
- Convert a Unix timestamp to a specified date and time format.
SELECT FROM_UNIXTIME(1641024000, '%Y-%m-%d %H:%i:%s');
Output: January 1, 2022, 12:00:00 AM
- Convert a Unix timestamp to a date format represented in Chinese.
SELECT FROM_UNIXTIME(1641024000, '%Y年%m月%d日');
Output: January 01, 2022
It is important to note that the from_unixtime function in MySQL is used for converting integer Unix timestamps. If the input is in string type, it needs to be converted to integer type using the unix_timestamp function before using the from_unixtime function.