ADDING DAYS WEEKS OR MONTHS TO DATES - Dec 5th, 2012


When I was creating the on-line version of this cookbook, I wanted to be able to show NEW or REVISED recipes for a
period of 30 days.

Fortunately, using PHP it's pretty easy to add (or subtract) days, weeks, or months, to a date. The trick is that you
have to convert your dates into UnixTime (seconds since 1970) before you can successfully add ore subtract the values.

Here's how I accomplished my goal.

First I created 2 checkboxes fields in my editor. One for New and one for REVISED.

Then I defined the date and time variables that I needed to compare. (Current UnixTime is shown for clarity of this
recipe) and placed the code within my foreach loop.



<?PHP
$newUnixTime = strtotime($record['createdDate']); // seconds since 1970 to createdDate
$updateUnixTime = strtotime( $record['updatedDate'] ); // seconds since 1970 to updateDate
$currentUnixTime = strtotime(date('Y-m-d'));
$pastUnixTime = strtotime(date('Y-m-d', strtotime("-30 day")));
$newdifference = $newUnixTime - $pastUnixTime ;
$updatedifference = $updateUnixTime - $pastUnixTime ;
?>



Once the variables were determined, it was a matter of comparing them and outputting the correct information based on
the result.



<!-- Check For New Or Revised Date -->
<?php if ($record['new'] == 1 && $newdifference >= 0): ?><span class="Medium-Text-Bold-Red">NEW</span><?php endif ?>
<?php if ($record['revised'] == 1 && $updatedifference >= 0): ?><span class="Medium-Text-Bold-Red">REVISED</span><span
class="Medium-Text-Bold"> - </span><?php endif ?>
<!-- End Date Check -->



Some other examples of adding to and subtracting from dates.



$add_a_week = strtotime(date('Y-m-d', strtotime("+1 week")));
$subtract_2_months = strtotime(date('Y-m-d', strtotime("-2 month")));




The materials on this web site have been created for use with CMS Builder content management software. CMS Builder software is published and licensed for use by InteractiveTools.com. Please contact Interactive Tools for information on the downloading of the software or the purchasing of licenses.


Terms of Service