Working with dates and times is very common in programming, let’s see what PHP provides.
We can get the current timestamp (number of seconds since Jan 1 1970 00:00:00 GMT) using
$timestamp = time();
When you have a timestamp you can format that as date using
date(), using the format you prefer:
echo date('Y-m-d', $timestamp);
Y is the 4-digits representation of the year,
m is the month number (with leading zero) and
d is the number of day of the month, with leading zero.
We can convert any date into a timestamp using
strtotime(), which takes a string with a textual representation of a date and converts it into the number of seconds since Jan 1 1970:
echo strtotime('now'); echo strtotime('4 May 2020'); echo strtotime('+1 day'); echo strtotime('+1 month'); echo strtotime('last Sunday');
..it’s pretty flexible.
For dates it’s common to use libraries that offer a lot more functionality than what the language can. A good option is Carbon.
Download my free PHP Handbook!