Home > Article > Backend Development > Three commonly used ways to format dates into strings in PHP
There are many functions for converting date formats in PHP. This article will introduce three common ways to format dates into strings.
The date() function in PHP can format a Unix timestamp into a readable date and time string. Among them, the first parameter is the date format to be converted, and the second parameter is the Unix timestamp (the default is the timestamp of the current time).
For example, format the current time into a string in the "Y-m-d H:i:s" format:
echo date("Y-m-d H:i:s");
Output:
2022-03-22 11:30:00
The strftime() function can also format Unix timestamps into readable date and time strings, but it can support localized display of date and time. It can use different date and time formats depending on local environment configuration.
Unlike the date() function, the strftime() function requires two parameters. The first parameter is the formatted string to display the date and time, and the second parameter is the Unix timestamp. The following is an example:
setlocale(LC_TIME, "zh_CN.utf8"); echo strftime("%Y-%m-%d %H:%M:%S", time());
In this example, the setlocale() function sets the local environment of the date and time to Simplified Chinese UTF-8 encoding, and the strftime() function uses "Y-m-d H:i:s " format string formats the timestamp into a readable date and time string.
Output:
2022-03-22 11:30:00
The DateTime class in PHP provides a more object-oriented way of handling dates and times. It allows to represent dates and times by creating DateTime objects and converting them to strings via the format() method.
For example, the following code creates a DateTime object and formats it into a string in the specified format:
$date = new DateTime(); echo $date->format("Y-m-d H:i:s");
Output:
2022-03-22 11:30:00
Summary
This article introduces three commonly used ways to format dates into strings, namely the date() function, strftime() function and DateTime class. Different scenarios and needs allow you to choose different methods for date format conversion.
The above is the detailed content of Three commonly used ways to format dates into strings in PHP. For more information, please follow other related articles on the PHP Chinese website!