Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 424
Felix Eve Avatar asked Nov 04 '13 16:11

Felix Eve


People also ask

How is financial year calculated?

For instance, if your financial year is from 1 April 2020 to 31 March 2021, then it is known as FY 2020-21. The assessment year for the money earned during this period would begin after the financial year ends – that is from 1 April 2021 to 31 March 2022. Hence, the assessment year would be AY 2022-22.

How can get current year start and end date in PHP?

$year = date('Y') - 1; // Get current year and subtract 1 $start = "January 1st, {$year}"; $end = "December 31st, {$year}"; If you need the timestamp for both those dates: $year = date('Y') - 1; // Get current year and subtract 1 $start = mktime(0, 0, 0, 1, 1, $year); $end = mktime(0, 0, 0, 12, 31, $year);


2 Answers

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") );
like image 72
Luca Rainone Avatar answered Oct 07 '22 13:10

Luca Rainone


Just as fun I throw this into the mix for you

echo date('l jS F (Y-m-d)', strtotime('first thursday january this year'));

Try it You can then check if it is 1st ?

obviously you will need the format correct for checking etc

I love these PHP quirks

like image 42
Shaun Hare Avatar answered Oct 07 '22 11:10

Shaun Hare