开发者

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?


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.


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.


For the reason why you can't go before 1970 or past 2038 see the date manual:

The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜