Home >Backend Development >PHP Problem >How to convert php time to unix timestamp
In PHP programming, time conversion is often a common problem, especially converting time to UNIX timestamp. A UNIX timestamp is the number of seconds since January 1, 1970, and is one of the most commonly used time representations in computer systems. In PHP, there are many ways to convert time to UNIX timestamp. Let’s introduce them in detail below.
The strtotime function is one of the built-in date functions in PHP, which can convert a date and time string into a UNIX timestamp. For example:
$date = '2022-04-01 12:00:00'; $unix_time = strtotime($date); echo $unix_time;
The output will be: 1648849200
, which represents the UNIX timestamp at 12 o'clock on April 1, 2022.
DateTime is a built-in class in PHP that provides many useful date and time processing methods, including converting datetime objects to UNIX timestamp.
$date_str = '2022-04-01 12:00:00'; $datetime = new DateTime($date_str); $unix_time = $datetime->format('U'); echo $unix_time;
Here, we create a DateTime object and use the format method to convert the object to UNIX timestamp format. The output result is the same as the above example: 1648849200
.
The mktime function is another built-in function in PHP, which can return the corresponding UNIX timestamp according to the given time parameter. For example:
$hour = 12; $minute = 0; $second = 0; $month = 4; $day = 1; $year = 2022; $unix_time = mktime($hour, $minute, $second, $month, $day, $year); echo $unix_time;
This code will give the time parameter of 12:00:00 on April 1, 2022, and use the mktime function to convert it to a UNIX timestamp. The output is the same as the previous two examples.
Summary:
As can be seen from the above three examples, converting time to UNIX timestamp is not difficult in PHP. Whether you use the strtotime function, DateTime class, or mktime function, as long as you master the corresponding usage methods, you can easily complete this conversion operation. In addition, you also need to pay attention to time zone issues to ensure the accuracy of time conversion.
The above is the detailed content of How to convert php time to unix timestamp. For more information, please follow other related articles on the PHP Chinese website!