PHP Method for Getting All Dates of the Week or All Dates of the Last Seven Days

  • 2021-10-24 19:11:25
  • OfStack

This article mainly introduces how php can get all the dates of this week or the last 7 days. I hope I can help friends in need

Get all dates of the week:


/**
 *  Get all dates of the week 
 */
function get_week($time = '', $format='Y-m-d'){
  $time = $time != '' ? $time : time();
  // Get the current day of the week 
  $week = date('w', $time);
  $date = [];
  for ($i=1; $i<=7; $i++){
    $date[$i] = date($format ,strtotime( '+' . $i-$week .' days', $time));
  }
  return $date;
}

Implementation results:


print_r(get_week());
Array
(
  [1] => 2018-06-18
  [2] => 2018-06-19
  [3] => 2018-06-20
  [4] => 2018-06-21
  [5] => 2018-06-22
  [6] => 2018-06-23
  [7] => 2018-06-24
)

Get the last 7 days:


/**
 *  Get the most recent 7 Days All Dates 
 */
function get_weeks($time = '', $format='Y-m-d'){
  $time = $time != '' ? $time : time();
  // Combined data 
  $date = [];
  for ($i=1; $i<=7; $i++){
    $date[$i] = date($format ,strtotime( '+' . $i-7 .' days', $time));
  }
  return $date;
}

Implementation results:


print_r(get_weeks());
Array
(
  [1] => 2018-06-13
  [2] => 2018-06-14
  [3] => 2018-06-15
  [4] => 2018-06-16
  [5] => 2018-06-17
  [6] => 2018-06-18
  [7] => 2018-06-19
)

Summarize


Related articles: