Search code examples
phpdatefinancial

PHP Calculate Start of Financial Year


The company I'm working for has a financial year that starts on 1st January if that is a Thursday, otherwise starts on the last Thursday of the previous year.

I've written a function that does this but it seem inefficient needing to loop:

function get_start_of_financial_year() {
    $date = date('Y').'-01-01';
    $correct_day = false;
    while(!$correct_day) {
        $day_num = date('N', strtotime($date));
        if($day_num==4) return $date;
        $date = date('Y-m-d', strtotime($date.' -1 day'));
    }
}

I've been trying something like this:

function get_start_of_financial_year() {
    $date = date('Y').'-01-01';
    $day_num = date('N', strtotime($date));
    $modifer = 4 - $day_num;
    return date('Y-m-d', strtotime($date.' -'.$modifer.' days'));
}

However this doesn't work. I know I'm doing something wrong when calculating my modifier, but what?

I've had a look at other similar questions / answers on here and are all slightly different so I think this is a genuine new question.


Solution

  • According to the doc

    "'last' dayname" takes the last dayname from the current day. (Example: "last wed july 2008" means "2008-06-25"; "july 2008" first sets the current date to "2008-07-01" and then "last wed" moves to the previous Wednesday which is "2008-06-25").

    So your case is

    function get_start_of_financial_year($year) {
        // get the first Thursday before 2 Jan of $year
        return date("Y-m-d", strtotime("last Thursday $year-01-02"));
    }
    
    echo get_start_of_financial_year( date("Y") );