Both PHP and MySQL support timestamps, but their respective timestamp formats are different, so timestamps need to be converted during data transmission and operations. This article will briefly introduce the formats of PHP and MySQL timestamps and how to convert between the two.
1. Timestamp format
The timestamp format in PHP is the UNIX timestamp format, which refers to the time since 1970 The number of seconds from 0:00:00 on January 1 to now, you can use the PHP built-in function time()
to get the current UNIX timestamp, for example:
$timestamp = time(); //获取当前UNIX时间戳 echo $timestamp; //输出当前UNIX时间戳
There are two timestamp formats in MySQL. One is an ordinary timestamp, which can be stored in the range 1970-01-01 00:00:01 to 2038-01-19 The time of 03:14:07, the other is the TIMESTAMP type, which can store a wider range of times, including from 0:00:1 on January 1, 1970 to 23:59:59 on December 31, 9999 , you can obtain the current timestamp in the following two ways:
SELECT UNIX_TIMESTAMP(); //获取当前UNIX时间戳 SELECT NOW(); //获取当前时间的TIMESTAMP类型
2. Timestamp conversion method
The timestamp in PHP can be converted to the timestamp format in MySQL through the built-in function date()
, for example:
$timestamp = time(); //获取当前UNIX时间戳 $mysql_timestamp = date('Y-m-d H:i:s', $timestamp); //将PHP时间戳转换为MySQL时间戳格式 echo $mysql_timestamp; //输出MySQL时间戳格式
The timestamp in MySQL can be converted to the UNIX timestamp format in PHP through the built-in function UNIX_TIMESTAMP()
, for example:
$mysql_timestamp = '2022-10-01 20:10:00'; //MySQL时间戳格式 $timestamp = strtotime($mysql_timestamp); //将MySQL时间戳格式转换为PHP时间戳格式 echo $timestamp; //输出PHP时间戳格式
3. Summary
Both PHP and MySQL support timestamps, but the formats of timestamps are different and need to be converted during data transmission and operation. The timestamp format in PHP is UNIX timestamp format. The timestamp format in MySQL includes ordinary timestamp and TIMESTAMP types, which can be obtained through built-in functions. When performing timestamp conversion, you can use PHP's date()
function to convert UNIX timestamps to MySQL timestamp format, or use PHP's strtotime()
function to convert MySQL timestamps The format is converted to UNIX timestamp format.
The above is the detailed content of How to convert php mysql timestamp. For more information, please follow other related articles on the PHP Chinese website!