Question

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.

Was it helpful?

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
?>

OTHER TIPS

Something like this:

function getLast() {
    $currentYear = date('Y');

    // Check if it happened this year, AND it's not in the future.
    $today = new DateTime();
    if (checkdate(3, 31, $currentYear) && $today->getTimestamp() > mktime(0, 0, 0, 3, 31, $currentYear)) {
        return $currentYear;
    }

    while (--$currentYear) {
        if (checkdate(3, 31, $currentYear)) {
            return $currentYear;
        }
    }

    return false;
}

var_dump(getLast());

It should return the year or false.

if (date('m')>3) {
    $year = date('Y').'-'.(date('Y')+1);
} else {
    $year = (date('Y')-1).'-'.date('Y');
}
echo $year;

this is to get the current financial year for India

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top