In the process of writing PHP code, sometimes you need to convert numbers into dates. For example, what is stored in the database is the numeric representation of a date field, and we need to display it in a human-readable date format on the web page. The following is an introduction to how to convert numbers into dates in PHP.
Usually, the date format represented by the number is a Unix timestamp, which is the number of seconds since January 1, 1970. For example, the number 1468531200 represents midnight on July 15, 2016 in the GMT time zone. There are multiple ways to convert Unix timestamp to date format in PHP, two of which are described below.
Method 1: Use the date() function
The date() function is a built-in function in PHP, used to format a local date/time. It has two parameters. The first parameter is a format string that specifies the format of the date/time you want to get. The second parameter is an optional timestamp specifying the date/time to format. If the second argument is not provided, the current local time is used by default. The following is an example:
$num = 1468531200; $format = "Y-m-d H:i:s"; $date = date($format, $num); echo $date;
Description:
In this example, the output result is "2016-07-15 00:00:00", that is, the number 1468531200 is converted into date format.
Method 2: Use the DateTime class
DateTime is a core class provided by PHP that can easily perform date/time operations. To convert Unix timestamp to date format, we can do it by instantiating DateTime class. The following is an example:
$num = 1468531200; $datetime = new DateTime("@$num"); $format = "Y-m-d H:i:s"; $date = $datetime->format($format); echo $date;
Description:
In this example, the output result is also "2016-07-15 00:00:00", that is, the number 1468531200 is converted into date format.
To sum up, the above two methods can convert numbers into dates. At the same time, it should be noted that when performing date/time operations, try to use standard time formats to avoid unnecessary trouble caused by time zones and other non-standard formats.
The above is the detailed content of Convert numbers to dates in php. For more information, please follow other related articles on the PHP Chinese website!