This code is a straight cut and paste from a comment the php.net page on the strftime() function, credit is due to lamb dot dan at gmail dot com.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php /* * This function figures out what fiscal year a specified date is in. * $inputDate - the date you wish to find the fiscal year for. (12/4/08) * $fyStartDate - the month and day your fiscal year starts. (7/1) * $fyEndDate - the month and day your fiscal year ends. (6/30) * $fy - returns the correct fiscal year */ function calculateFiscalYearForDate($inputDate, $fyStart, $fyEnd){ $date = strtotime($inputDate); $inputyear = strftime('%Y',$date); $fystartdate = strtotime($fyStart.$inputyear); $fyenddate = strtotime($fyEnd.$inputyear); if($date < $fyenddate){ $fy = intval($inputyear); }else{ $fy = intval(intval($inputyear) + 1); } return $fy; } // my fiscal year starts on July,1 and ends on June 30, so... echo calculateFiscalYearForDate("5/15/08","7/1","6/30"); // returns 2008 echo calculateFiscalYearForDate("12/1/08","7/1","6/30"); // returns 2009 ?> |
2 replies on “Calculating a fiscal year in PHP”
There are a couple of bugs in this code which prevent it from working as advertised.
$fystartdate = strtotime($fyStart.$inputyear);
$fyenddate = strtotime($fyEnd.$inputyear);
should be:
$fystartdate = strtotime($fyStart.'/'.$inputyear);
$fyenddate = strtotime($fyEnd.'/'.$inputyear);
And
if($date < $fyenddate){
should be:
if($date <= $fyenddate){
Hey Jason, thanks for your input.
I modified this so heavily to use it that I didn't run into that problem (though I haven't finished debugging so maybe I did.)
I'll look more closely at this when I get a chance, but I appreciate your comment.
Cheers,
Rob