Using PHP to find out a date, a period of time or the difference as text

Using PHP to find out a date, a period of time or the difference as text

In this post you will learn how to output times with PHP and also WordPress. This includes the current date; dates in the future, or in the past. Also how to find out days within a time period. Have fun!


With time() the current timestamp can be output. The current timestamp always consists of seconds. The starting date is always January 1, 1970 GMT. This means that time() always counts the seconds since January 1, 1970 GMT for us.

time(); // Now as timestamp

Since the seconds are printed here, the time can also be printed. For this we use date() to display the time.

date('H:i'); // Now as hour and minute


The best known and simplest function is the date() function provided by PHP. With this function you can easily output the current date.

date('d.m.Y'); // Now as date

As a second parameter you can also specify a timestamp. For example, a timestamp from the past will be prefixed as date.

date('d.m.Y', strtotime('-1 week')); // Now minus 1 week, as date


With strtotime() you can convert a date or time string into seconds. We used this function above to get Today a week ago.

strtotime('-1 weeks'); // Now a week ago

See also:


With the DateTime() class PHP offers us something really useful. The class can be used to modify, format and output strings.

$date = new \DateTime('now'); // Now

$date->modify('+2 days'); // Now plus two days
echo $date->format('d.m.Y'); // Return the result as date

$date->modify('+2 days'); // Now plus four days
echo $date->format('d.m.Y');

With getTimestamp() you can also return the timestamp. This is useful if you want to do comparisons.

$date = new \DateTime('01.01.2021'); // 01 January 2021

if ($date->getTimestamp() < time()) {
   echo 'January 01, 2021 is in the past!';


With DatePeriod() you can generate all days between two DateTime() objects. This is useful if you want to create a chart for example and also need the days between two dates.

$start = new \DateTime('01.01.2021');
$end = new \DateTime('15.01.2021');

$interval = new \DateInterval('P1D'); // P1D indicates that the days are counted
$period = new \DatePeriod($start, $interval,$end);

foreach ($period as $date) {
    echo $date->format('d.m.Y') . '<br>';

See also:

WordPress: human_time_diff()

With human_time_diff() WordPress offers us another useful function. With this you can calculate the distance between two timestamps. WordPress then converts this distance into a record.

For example, 1 week ago can be printed if the date is one week ago.

printf('before %s', human_time_diff(strtotime('-1 weeks')); // 1 week ago

See also:

Did you find this article valuable?

Support Kevin Pliester by becoming a sponsor. Any amount is appreciated!