Date interval add and sub prior to PHP 5.3

Summary

Prior to PHP 5.3, developers faced challenges with date interval manipulation due to the absence of the DateInterval object. A practical solution involves utilizing the strtotime() function to add or subtract time units. By passing relative date strings like '+1 day' or '-1 month' to strtotime(), one can effectively calculate future or past timestamps from a given date. This technique provides a robust way to manage date-based logic, such as setting deadlines or reminders, in applications running on older PHP versions.

After PHP 5.3, we can use DateInterval object or date_interval_create_from_date_string() function to add or subtract days,weeks,months or years to or from a DateObject.But prior to PHP 5.3,we cannot do this. If we want to achieve the same effect. We need to use some skills. Here is one:

We can use strtotime() function to achieve this. For example:
$date=date('Y-m-d',time());

$datestamp=strtotime(date('Y-m-d',strtotime($date)).' +1 day'); 
$datestamp=strtotime(date('Y-m-d',strtotime($date)).' +1 week');  
$datestamp=strtotime(date('Y-m-d',strtotime($date)).' +1 month');  

Here strtotime() will return a timestamp if success.

For subtraction,we can have:
$date=date('Y-m-d',time());

$datestamp=strtotime('-1 day',$strtotime($date));
$datestamp=strtotime('-1 week',$strtotime($date));
$datestamp=strtotime('-1 month',$strtotime($date));

We can use this when we want to set a deadline or remind date in our web application.

PHP CLASS DATEINTERVAL PHP 5.3 PHP 5.2

  RELATED

  COMMENTS

0

No comment for this article.