In developing web applications, converting time into timestamp is a very basic operation. PHP provides several built-in functions that make it easy to perform such conversions. This article explains how to convert time into timestamp using PHP.
The time() function returns the timestamp of the current time. If you want to get the timestamp of the current time, just use the time() function:
$timestamp = time(); echo $timestamp;
The strtotime() function can convert any format Convert a date string into a timestamp. For example, the following code converts the string "2019-06-01 12:00:00" into the corresponding timestamp:
$timestamp = strtotime("2019-06-01 12:00:00"); echo $timestamp;
If you want to convert the current time into a timestamp in a specified format, you can convert the date The string is passed to the strtotime() function as the second parameter:
$timestamp = strtotime("today"); echo $timestamp;
The above code will return the timestamp of the current date (hours, minutes, and seconds are all zero).
The DateTime class provides methods to convert dates into timestamps. The following is sample code that uses the DateTime class to convert a date to a timestamp:
$dateStr = '2019-07-01 12:00:00'; $dateTimeObj = new DateTime($dateStr, new DateTimeZone('UTC')); $timestamp = $dateTimeObj->format('U'); echo $timestamp;
The above code converts a date string into a DateTime object and converts it into a timestamp using the format() method.
The mktime() function accepts hours, minutes, seconds, months, days and years as parameters and returns the corresponding timestamp. The following is an example code that uses the mktime() function to convert a datetime into a corresponding timestamp:
$timestamp = mktime(0, 0, 0, 6, 1, 2019); echo $timestamp;
The above code converts a datetime (June 1, 2019) into a corresponding timestamp.
Summary
PHP provides a variety of methods to convert time into timestamps. The above introduces four methods of using the time() function, strtotime() function, DateTime class and mktime() function. You can choose any of them to use as needed.
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!