So why would you want to calculate a day of year to a date ?

Well I needed it for my Sudoku script. (http://sudoku.gebruikmaar.nl)
I wanted to show a new Sudoku every day, and let the visitors be able to show the sudoku of yesterday and the days before.


To get a “random” daily new sudoku I use the year day number. (so you’ve got 365 year days a year)
When going to the yesterday’s sudoku puzzle I do a day of year – 1.
But on the same screen I like to show the date.
So here you are…. I want to be able to calculate the date from the day of year I have choosen.
Here’s that code

$todayid = date("z");  // to get today's day of year

function dayofyear2date( $tDay, $tFormat = 'd-m-Y' ) {
    $day = intval( $tDay );
    $day = ( $day == 0 ) ? $day : $day - 1;
    $offset = intval( intval( $tDay ) * 86400 );
    $str = date( $tFormat, strtotime( 'Jan 1, ' . date( 'Y' ) ) + $offset );
    return( $str );
}

echo dayofyear2date($todayid);

ps: did you know that 1 year is not exactly 365 days ? 1 year is 365,242199 dagen
ps2: That is why the leap-year exists.

About the author

Theo van der Sluijs Theo van der Sluijs (1975) is Lead Developer at Unitrust BV. He is also creator of "I Am Bored So I blog" / Gebruikmaar.nl / vanderSluijs.nl. He is a member of the Board of the Dutch Flex Usergroup and Goesweb.net. With his quote "Never Give Up, Never Surrender" (Actually stolen from Galaxy Quest) he fights his way through the day. Connect with him on Twitter.

VN:F [1.9.3_1094]
Rating: 7.2/10 (5 votes cast)
VN:F [1.9.3_1094]
Rating: 0 (from 2 votes)
Calculate Date from day of year in PhP, 7.2 out of 10 based on 5 ratings

4 Responses to “Calculate Date from day of year in PhP”

  • JMP:

    I needed it for a gantt chart I am (attempting) to develop in Flex. Works great. Thanks

    VA:F [1.9.3_1094]
    Rating: 4.5/5 (2 votes cast)
    VA:F [1.9.3_1094]
    Rating: 0 (from 0 votes)
  • deb:

    Thank you ever so much! I was trying to avoid having to recode daily content with a datestamp! This will do the trick nicely without tons of typing. You rock!!

    VA:F [1.9.3_1094]
    Rating: 5.0/5 (1 vote cast)
    VA:F [1.9.3_1094]
    Rating: 0 (from 0 votes)
  • Christian Sciberras:

    Oh, and the right code would be:

    function dayofyear2date( $tDay, $tFormat = ‘d-m-Y’ ) {
    $offset = intval($tDay) * 86400;
    $date = mktime( 0, 0, 0, 1, 1, date(‘Y’) )+$offset;
    return date( $tFormat, $date );
    }

    $todayid = date(“z”); // to get today’s day of year
    echo dayofyear2date($todayid);

    VA:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.3_1094]
    Rating: 0 (from 0 votes)

Leave a Reply

QR Code
Donate

Like the information on my site? Please donate for a cup of coffee, or give a bit more for a cappuccino.

Twitter
Get Adobe Flash playerPlugin by wpburn.com wordpress themes