Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php program to find the my birthday where day name "Monday" for another 100 years

I was born in 1986-04-21, which is Monday. My next birthday with day name "Monday" is 1997-04-21 and so on.

I wrote the program to find upto 100 year to find which year my birthday comes with matching day name that is monday.

This is the code:

<?php
date_default_timezone_set('Asia/Calcutta');
for($year = 1986; $year < 2086; $year++) {
    $timestamp = mktime(0, 0, 0, 4, 21, $year);
    if(date('l', $timestamp) == 'Monday') {
        echo date('Y-m-d, l', $timestamp) . "\n";
    }
}
?>

This is the output of the program:

1986-04-21, Monday
1997-04-21, Monday
2003-04-21, Monday
2008-04-21, Monday
2014-04-21, Monday
2025-04-21, Monday
2031-04-21, Monday
2036-04-21, Monday

Now my problem is why PHP is not supporting before 1970 and after 2040.
So how can I get the birthday after 2040 or before 1970?

like image 844
Madan Sapkota Avatar asked Dec 13 '22 12:12

Madan Sapkota


2 Answers

There's no need to use any special date processing classes or functions at all.

Your birthday is after the leap day in February, so from one year to the next it'll either be one day (365 % 7) or (on leap years) two days (366 % 7) later in the week than it was the year before.

$year = 1985; // start year
$dow = 0;     // 0 for 1985-04-21 (Sunday)

while ($year < 2100) {

    $year++; $dow++;

    if ($year % 4 == 0 && ($year % 100 != 0 || $year % 400 == 0)) {
       $dow++; // leap year
    }

    $dow %= 7;      // normalise back to Sunday -> Saturday
    if ($dow == 1) {
        printf("%04d-%02d-%02d is a Monday\n", $year, 4, 21);
    }
}

This code will work on any version of PHP.

like image 185
Alnitak Avatar answered Dec 15 '22 02:12

Alnitak


If you're on PHP 5.3, you can use the DateTime class and add DateIntervals. It is based on 64-bit integers and doesn't have the year 2038 problem.

Basic example:

<?php

$year = DateInterval::createFromDateString('1 year'); 

$date = new DateTime('1986-04-21');
$date->add($year);
echo $date->format('Y-m-d') . "\n";  // Repeat 100 times

documentation on createFromDateString() is here.

like image 40
Pekka Avatar answered Dec 15 '22 02:12

Pekka