In PHP, date and time formatting refers to the process of converting date and time from a machine-readable format into a human-readable format. Date and time formatting is a common requirement in websites and applications, as it is used to display the current date and time, as well as format past and future dates and times.
PHP provides several built-in functions for handling dates and times. Below are some commonly used functions:
The date() function is the most commonly used function in PHP for formatting dates and times. It allows you to format a date and time in any format you need. Here’s a simple example:
In the example above, the date() function formats the current date and time as "Y-m-d H:i:s". The meaning of each format specifier is as follows:
In addition to the format specifiers mentioned above, there are many other format specifiers you can refer to in the official PHP documentation.
The strtotime() function can parse any English textual datetime description into a Unix timestamp. Here’s an example:
In this example, we use the strtotime() function to parse the given textual datetime into a Unix timestamp.
The strftime() function is similar to the date() function, but it has more format specifiers (e.g., %a represents the day of the week). Here’s an example:
In the example above, we use the strftime() function to format the current date and time as "Y-m-d H:i:s". The format specifiers %Y, %m, %d, %H, %M, and %S have the same meaning as those in the date() function.
In PHP, you can calculate dates and times using Unix timestamps. A timestamp represents the number of seconds since January 1, 1970, 00:00:00 GMT.
Here’s an example of calculating a future date:
In this example, we use the time() function to get the current Unix timestamp, add one week’s worth of seconds to it, and then use the date() function to format the new date as "Y-m-d H:i:s".
In addition to using timestamps, you can also use the strtotime() function to calculate dates and times. Here’s an example of calculating a future date:
In this example, we use the strtotime() function to calculate the date one week from today and format the result as "Y-m-d H:i:s".
This article introduced several methods for formatting dates and times in PHP, including using the built-in date() and strftime() functions, parsing datetime text using the strtotime() function, and calculating dates and times using timestamps and strtotime().