简体   繁体   中英

Split a single date range into two separate date range with a given date

I'm trying to split a single date range into two separate date ranges with a given last date using PHP.

For example, this date range '2016-01-01 00:00:00' to '2019-02-14 23:59:59' will have these two date ranges below. Given that the separate date is 2018-01-01.

  1. '2016-01-01 00:00:00' - '2017-12-31 23:59:59'
  2. '2018-01-01 00:00:00' - '2019-02-14 23:59:59'

Sample code like below.

$start = '2016-01-01 00:00:00';
$end = '2019-02-14 23:59:59';
$sepDate = '2018-01-01';
$dateRange = separateDate($start, $end, $sepDate);

function separateDate($start, $end, $sepDate){
    //separate date function 
}

Output:
$dateRange[0]['start']  //'2016-01-01 00:00:00'
$dateRange[0]['end']    //'2017-12-31 23:59:59'

$dateRange[1]['start']  //'2018-01-01 00:00:00'
$dateRange[1]['end']    //'2019-02-14 23:59:59'

This can be done fairly simple. Just convert the separator to a timestamp, this way you can subtract one second to get the end date of the first period. The rest is pretty straightforward.

function separateDate($start, $end, $sepDate){
    return [
        [
            "start" => strtotime($start),
            "end" => strtotime($sepDate) - 1
        ],
        [
            "start" => strtotime($sepDate),
            "end" => strtotime($end)
        ]
    ];
}

I converted all datetimes to timestamps to keep the output consistent. It's not that hard to turn them into dates again.

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