Search code examples
phpdatefinancial

PHP to calculate latest 31 March


i want to calculate latest 31-Mar .... suppose date is 1-Jan-2012 i want result as 31-mar-2011 and if is 1-April-2011 then also i want result 31-mar-2011 and if its 1-mar-2011 it should come as 31-mar-2010.....hope i made my self clear ...(with php) ... i al calculating date with this for financial year ... always between 31-mar-lastyear to 1-April-thisyear ... year should be taken automatically ... i was trying like this

31-mar-date('y') and 31-mar-date('y')-1

but its not working as its taking current year every time.


Solution

  • Here is an example using the wonderful strtotime function of php.

    <?php
    
    $day = 1;
    $month = 1;
    $year = 2011;
    
    $date = mktime(12, 0, 0, $month, $day, $year);
    
    $targetMonth = 3;
    $difference = $month - $targetMonth;
    
    if($difference < 0) {
        $difference += 12;
    }
    
    $sameDateInMarch = strtotime("- " . $difference . " months", $date);
    
    echo "Entered date: " . date("d M Y", $date) . "<br />";
    echo "Last 31 march: " .  date("t M Y", $sameDateInMarch);
    
    // the parameter 't' displays the last day of the month
    ?>