简体   繁体   中英

Find a date range from a date

How would you solve the problem below?

On a given date, I'd like to find the range of an academic year. The academic years always start on the first of September and lasts until the last of August. Thus, for today (2015-07-16) I would like the function return the dates 2014-09-01 and 2015-08-31. If I were to run the same function in three months (2015-10-16) I'd like to get 2015-09-01 and 2016-08-31 returned.

Thank you,

/Thomas

-- edit requested by @anant-kumar-singh --

An example function in PHP:

function getAcademicYear($date) {
    // Logic code...
    return array($dateStart, $dateEnd);
}

Calling getAcademicYear('2015-07-16'); should return the array, ['2014-09-01','2015-08-31']

And calling getAcademicYear('2015-10-16'); should return the array, ['2015-09-01','2016-08-31']

-- edit --

function findAcademicYear($date) {
    $dateTime = new DateTime($date);
    $dateTime->sub(new DateInterval("P8M"));
    return(array(
        "startDate" => date("Y-m-d", strtotime($dateTime->format("Y")."-08-31 + 1 day")),
        "endDate" => ($dateTime->format("Y") + 1)."-08-31")
        );
}

I would use the following logic: Subtract 8 months from the date, extract the year, and use that for the specification of the year:

select date(concat(year(date_sub(date, interval 8 month)), '-09-01')) as academic_start,
       date(concat(1 + year(date_sub(date, interval 8 month)), '-08-31')) as academic_end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM