Calculate Date from day of year in PhP
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.





I needed it for a gantt chart I am (attempting) to develop in Flex. Works great. Thanks
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!!
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);
Thanks Christian, this new code looks great.
Actually, the right right code would be:
function dayofyear2date( $tDay, $tFormat = 'd-m-Y' ) {
$date = mktime( 0, 0, 0, 1, $tDay, date('Y') );
return date( $tFormat, $date );
}
$todayid = date("z"); // to get today's day of year
echo dayofyear2date($todayid);
actually the correct function will be
function dayofyear2date( $tDay, $tFormat = 'd-m-Y' ) {
$date = mktime( 0, 0, 0, 1, $tDay+1, date('Y') );
return date( $tFormat, $date );
}
$todayid = date("z"); // to get today's day of year
echo dayofyear2date($todayid);
Beacuse date('z') starts from 0 and mktime count the number of days from 1
Thank you very much, I could'nt find an alternative to your function.. you really saved my time..
I could have never figured it out (within 2 or 3 weeks!!), thank you!
Things are even more simple:
function DayToTimestamp($day, $year = null) {
isset($year) or $year = date('Y');
return strtotime("1 Jan $year +$day day");
}
Thx