Home  >  Article  >  Backend Development  >  Detailed explanation of how to convert PHP string to Datetime

Detailed explanation of how to convert PHP string to Datetime

PHPz
PHPzOriginal
2024-03-22 14:36:041112browse

Detailed explanation of how to convert PHP string to Datetime

PHP is a powerful server-side scripting language widely used for web development. In PHP, handling time and date is one of the very common tasks. In practical applications, it often involves converting strings to Datetime types. This article will introduce in detail the method of converting string to Datetime in PHP and provide specific code examples.

1. Use the strtotime() function

strtotime() function is a commonly used function in PHP to convert a string into a timestamp. The strtotime() function can easily convert strings in various date and time formats into Datetime types.

The following is a sample code:

$dateStr = "2021-07-15 14:30:00";
$datetime = date_create(date("Y-m-d H:i:s", strtotime($dateStr)));
echo date_format($datetime, "Y-m-d H:i:s");

Run the above code, the output result will be: "2021-07-15 14:30:00", indicating that the string is successfully converted to Datetime type.

2. Use the DateTime class

PHP provides the DateTime class to handle date and time, and the DateTime class can be used flexibly Convert date and time formats locally.

The following is a sample code:

$dateStr = "2021-07-15 14:30:00";
$datetime = new DateTime($dateStr);
echo $datetime->format("Y-m-d H:i:s");

Run the above code, you can also successfully convert the string to Datetime type, and the output result is: "2021-07-15 14:30: 00".

3. Use date_create_from_format()Function

date_create_from_format()The function can specify the input date and time format and convert the string into Datetime type .

The following is a sample code:

$dateStr = "15-07-2021 14:30:00";
$datetime = date_create_from_format("d-m-Y H:i:s", $dateStr);
echo date_format($datetime, "Y-m-d H:i:s");

Run the above code, you can also successfully convert the string to Datetime type, and the output result is: "2021-07-15 14:30: 00".

Through the above introduction, we have a detailed understanding of the method of converting strings to Datetime types in PHP and provide specific code examples. In practical applications, choosing the appropriate method can easily handle date and time conversion, improving development efficiency and code readability.

The above is the detailed content of Detailed explanation of how to convert PHP string to Datetime. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn