Calculate Future or Past date in PHP

This tutorial will show you how can you calculate either future date from a particular date to “plus a number of given days” or past date from a particular date to “minus a number of given days”. Future or past date calculation may be required for various purposes such as to calculate the age of a person on future date or on past date.

I will show you this calculation in PHP language. If you need to calculate in Java please read here https://roytuts.com/future-or-past-date-in-java/

You first need to setup an appropriate timezone otherwise php sometimes give warnings. I have set “Asia/Kolkata”, you can set according to your timezone.

Related Posts:

Prerequisites

PHP 7.4.3, Apache HTTP Server 2.4

Calculate Future or Past Dates

In this section I am going calculate future or past dates from a given date or current date.

<?php

date_default_timezone_set('Asia/Kolkata');
$date_format = 'Y-m-d'; //date format
$date = "2015-02-25"; //date from which the next or past date will be calculated
$curr_date = date('Y-m-d');

$future_date = date($date_format, strtotime($date . ' + 280 days')); //future date after adding 280 days to the above date
echo 'Future Date : ' . $future_date . '(' . $date_format . ')';
echo nl2br("\r\n");
echo 'Future Date with respect to current date: ' . date($date_format, strtotime($curr_date . ' + 280 days'));
echo nl2br("\r\n");
echo "===================================================";
echo nl2br("\r\n");
$past_date = date($date_format, strtotime($date . ' - 30 days')); //past date after subtracting 30 days from the above date
echo 'Past date : ' . $past_date . '(' . $date_format . ')';
echo nl2br("\r\n");
echo 'Past date with respect to current date: ' . date($date_format, strtotime($curr_date . ' - 30 days'));

echo nl2br("\r\n");
echo nl2br("\r\n");
echo 'Other textual values that get converted into Unix timestamps';
echo nl2br("\r\n");
echo "==============================================================";
echo nl2br("\r\n");
echo(strtotime("now") . "<br>");
echo(strtotime("3 October 2005") . "<br>");
echo(strtotime("+5 hours") . "<br>");
echo(strtotime("+1 week") . "<br>");
echo(strtotime("+1 week 3 days 7 hours 5 seconds") . "<br>");
echo(strtotime("next Monday") . "<br>");
echo(strtotime("last Sunday"));

I have used strtotime() function that converts English textual date time into equivalent Unix timestamp. In the above example I am adding 280 days to calculate the future date and subtracting 30 days to calculate the past date.

Testing the App

Execute the above script in the browser using the URL http://localhost/php-past-future-date/php-past-future-date.php, you will see the following output:

future or past date php

That’s all about how to calculate future or past date using PHP program.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *