Home > Article > Backend Development > Comprehensive understanding of string to Datetime operations in PHP
Converting strings to Datetime types in PHP is one of the common operations in development. It can help us convert date strings into Datetime objects for date-related operations. This article will introduce the specific operation and sample code of converting string to Datetime in PHP.
In PHP, we can use the strtotime()
function and the DateTime
class to convert the string Convert to Datetime object. Next, we will introduce these two methods respectively.
strtotime()
Functionstrtotime()
The function can convert a string containing date and time information into a UNIX timestamp, and then Use the date()
function to convert it to a Datetime object. The example is as follows:
<?php $dateStr = "2022-01-01 12:00:00"; $timestamp = strtotime($dateStr); $datetime = new DateTime(); $datetime->setTimestamp($timestamp); echo $datetime->format('Y-m-d H:i:s'); ?>
DateTime
classDateTime
class to directly convert a string into a Datetime object. The example is as follows:
<?php $dateStr = "2022-01-01 12:00:00"; $datetime = new DateTime($dateStr); echo $datetime->format('Y-m-d H:i:s'); ?>
The following will combine the above two methods to give a complete sample code:
<?php // 使用strtotime()函数 $dateStr = "2022-01-01 12:00:00"; $timestamp = strtotime($dateStr); $datetime1 = new DateTime(); $datetime1->setTimestamp($timestamp); // 使用DateTime类 $datetime2 = new DateTime("2022-01-01 12:00:00"); echo "通过strtotime()函数转换的Datetime对象:".$datetime1->format('Y-m-d H:i:s')."<br>"; echo "通过DateTime类转换的Datetime对象:".$datetime2->format('Y-m-d H:i:s')."<br>"; ?>
In the above sample code, we first use ## The #strtotime() function and
DateTime class convert the date string into a Datetime object, and then output the converted Datetime object.
The above is the detailed content of Comprehensive understanding of string to Datetime operations in PHP. For more information, please follow other related articles on the PHP Chinese website!