简体   繁体   中英

How to get date range of 7 days before and after of given date and populate in select - Laravel

I am trying to get date list of 7 dates before and after of a specific date in select field in laravel. For Example if a specific date is "2019-07-18", I want to populate date list from "2019-07-11" to "2019-07-25" in select field. Can anyone help me with code snippet for controller achieve this.

You can use carbon period :

$givenDate = "2019-07-18";
$dateMinusOneWeek = Carbon::parse($givenDate)->subWeek()->format('Y-m-d');
$datePlusOneWeek = Carbon::parse($givenDate)->addWeek()->format('Y-m-d');

$period = CarbonPeriod::create(dateMinusOneWeek , datePlusOneWeek);

//You can iterate over the period
foreach ($period as $date) {
    echo $date->format('Y-m-d');
}

//Or convert the period to an array of dates
$dates = $period->toArray();

Hope it helps.

function getAgoDays($specDay, $days, $format = 'Y-m-d') {
    $d = date('d', strtotime($specDay)); 
    $m = date('m', strtotime($specDay)); 
    $y = date('Y', strtotime($specDay));
    $dateArray = array();
    for($i=1; $i<=$days; $i++) {
        $dateArray[] = '"' . date($format, mktime(0,0,0,$m,($d-$i),$y)) . '"'; 
    }
    return array_reverse($dateArray);
}
function getBeforeDays($specDay, $days, $format = 'Y-m-d') {
    $d = date('d', strtotime($specDay)); 
    $m = date('m', strtotime($specDay)); 
    $y = date('Y', strtotime($specDay));
    $dateArray = array();
    for($i=1; $i<=$days; $i++) {
        $dateArray[] = '"' . date($format, mktime(0,0,0,$m,($d+$i),$y)) . '"'; 
    }
    return $dateArray;
}

use

$agoDays = getAgoDays('2019-07-18', 7, 'Y-m-d');
echo '<pre>';
print_r($agoDays);
echo '</pre>';
$agoDays = getBeforeDays('2019-07-18', 7, 'Y-m-d');
echo '<pre>';
print_r($agoDays);
echo '</pre>';

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