PHPRO.ORG

Calculate Friday The 13th With Datetime Class

Calculate Friday The 13th With Datetime Class

By Kevin Waterson

This class is a request from a PHPRO.ORG regular who asked for a method to calculate Friday the 13th for the next n years. The calculation itself is easy, however, it presents a good opportunity to introduce the PHP datetime class.

Timestamps have limitted uses as 2038 draws closer and strtotime will not serve the purpose should a range of dates beyond 2038 be required. The PHP datetime class will allow date calculations beyond this date. The datetime class will also take into account leap years according to the gregorian calendar.

The datetime class has many functions to enable safe date calculations and manipulations and even cloning o f the instance as demonstrated below. The modify() method is destructive. This means modifications occur on the instance itself, so if a copy is required, the clone method is used.


<?php

    
/**
     *
     * @get all friday the thirteenth for n years
     *
     * @param int $years
     *
     * @param string $timezone
     *
     * @return array
     *
     */
    
function fridayThirteen($years$timezone='UTC')
    {
        
/*** set the timezone ***/
        
date_default_timezone_set($timezone);

        
/*** the start date ***/
        
$start = new DateTime('friday');

        
/*** the end date ***/
        
$end = clone $start;
        
$end->modify("+$years years");

        
/*** an array to store the date objects ***/
        
$arr = array();

        
/*** the date class allows comparisons ***/
        
while($start $end)
        {
            if(
$start->format('l j') == 'Friday 13')
            {
                
$arr[] = clone $start;
            }
            
$start->modify('+7 days');
        }
        return 
$arr;
    }
?>

Example Usage


<?php
        $friday13 
fridayThirteen(20);
        foreach(
$friday13 as $date)
        {
                echo 
$date->format('D j M Y')."<br />";
        }
?>

Demonstration

Fri 13 Feb 2015
Fri 13 Mar 2015
Fri 13 Nov 2015
Fri 13 May 2016
Fri 13 Jan 2017
Fri 13 Oct 2017
Fri 13 Apr 2018
Fri 13 Jul 2018
Fri 13 Sep 2019
Fri 13 Dec 2019
Fri 13 Mar 2020
Fri 13 Nov 2020
Fri 13 Aug 2021
Fri 13 May 2022
Fri 13 Jan 2023
Fri 13 Oct 2023
Fri 13 Sep 2024
Fri 13 Dec 2024
Fri 13 Jun 2025
Fri 13 Feb 2026
Fri 13 Mar 2026
Fri 13 Nov 2026
Fri 13 Aug 2027
Fri 13 Oct 2028
Fri 13 Apr 2029
Fri 13 Jul 2029
Fri 13 Sep 2030
Fri 13 Dec 2030
Fri 13 Jun 2031
Fri 13 Feb 2032
Fri 13 Aug 2032
Fri 13 May 2033
Fri 13 Jan 2034