PHP: Calculating a Real Date using the Day of the Year

March 12th, 2006

Using the day of the year is a great way to denote dates in a database, but it’s hard to convert into a usable date stamp. The following code will return the current day of the year:

$dayofyear = date( 'z' );

This function will take the value of $dayofyear and calculate the proper date stamp and return as specified by the $pFormat parameter:

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

This is a bit of a hack, so let me explain the function’s logic:

The Day of the Year is an integer, so the first thing the function does is to make sure the passed parameter $pDay is an integer.

The next thing the function does is to subtract 1 from the day, so you can use ‘1′ as the value of $pDay for the first day of the year, instead of ‘0′.

It then multiplies the day of the year ($day) by 86400, which is the number of seconds in a day. This gives us the number of seconds between Jan 1 and the day in question.

By adding the offset to the number of seconds since epoch for Jan 1, we now have the number of seconds since epoch for the current day.

This seconds value is usable by PHP’s date function, so we can now get our properly formatted date stamp.