In PHP development, converting time into timestamp is a very common operation. A timestamp is a number that represents time, usually the number of seconds since January 1, 1970 00:00:00 GMT (Greenwich Mean Time). In this article, we will focus on how to convert time to timestamp in PHP.
The strtotime() function is one of the most commonly used methods in PHP to convert time into a timestamp. This function converts a time in string form to a UNIX timestamp.
Sample code:
$time = strtotime('2022-01-01 00:00:00'); echo $time;
Running the above code will output the timestamp of that time, and the result is:
1640995200
PHP also provides a DateTime object, which can easily calculate and format time. We can use DateTime object to convert time into timestamp. The specific implementation is as follows:
Sample code:
$datetime = new DateTime('2022-01-01 00:00:00'); echo $datetime->format('U');
Running the above code will output the timestamp of that time, and the result is the same as the previous example.
The mktime() function is a common method for converting dates into UNIX timestamps. This function accepts hours, minutes, seconds, and parameters representing months, days, and years, and returns a UNIX timestamp.
Sample code:
$timestamp = mktime(0, 0, 0, 1, 1, 2022); echo $timestamp;
Running the above code will output the timestamp of that time, and the result is the same as the previous example.
You can also use the intval() function to convert the date into a UNIX timestamp. This function accepts a string parameter representing a date and uses the strtotime() function to convert it to a timestamp.
Sample code:
$timestamp = intval(strtotime('2022-01-01 00:00:00')); echo $timestamp;
Running the above code will output the timestamp of that time, and the result is the same as the previous example.
Summary:
This article introduces four methods of converting time into timestamp in PHP, using strtotime() function, time object, mktime() function and intval() function. Different application scenarios can choose different methods. Mastering these common time processing methods can enable us to handle time-related tasks more efficiently in PHP development.
The above is the detailed content of How to convert time to timestamp in php. For more information, please follow other related articles on the PHP Chinese website!