Here is a simple first of several notes on useful date functions. This function accepts a year (YYYY) and a Day in the year (1 to 366), and returns a DateTime Object.
/* Year if format YYYY, Day in year 1 to 366 */function dayofyear2date( $year, $DayInYear ) {
$d = new DateTime($year.'-01-01');
date_modify($d, '+'.($DayInYear-1).' days');
return ($d);
}
I’m tired of seeing Unix time stamp code examples that break with older dates. Since my ical calendar scripts can potentially hold recurring dates that are anniversaries and birthdays, my scripts need to cope with dates earlier than 1970, and with timezones and daylight saving, so I use the DateTime class exclusively now.
Test Script To Check Function
<?php
function dayofyear2date( $year, $DayInYear ) {
$d = new DateTime($year.'-01-01');
date_modify($d, '+'.($DayInYear-1).' days');
return ($d);
}
$d[] = new DateTime('1950-12-31');
$d[] = new DateTime('1970-01-01');
$d[] = new DateTime('2010-01-01');
$d[] = new DateTime('2010-12-27');
$d[] = new DateTime('2010-12-31');
foreach ($d as $i => $d2) {
$dayofyear = $d2->format('z')+1;
$date = dayofyear2date (
$d2->format('Y'),
$dayofyear ); /* note z returns days from 0 */
echo '<br /><b>'.$d2->format('Y m d')
.'</b> '.$dayofyear.' <br />'
.$date->format('Y m d');
}
?>
Related posts:
- Get the next, or previous day of week from the current date Given a date, get the next or previous Monday, or Tuesday etc from the given date. This is useful when...
- Day of week for historical dates earlier than 1760 Problem with getting the day of week for old dates before 1760? See this....
- Comparison of Event Calendar Plug-ins We are thinking of converting the school’s website from typo3 to wordpress to make it easier for staff and parents...



