Home  >  Article  >  Backend Development  >  PHP method to get all dates of this week or all dates of the last seven days

PHP method to get all dates of this week or all dates of the last seven days

jacklove
jackloveOriginal
2018-06-22 15:40:313187browse

This article mainly introduces how to get all the dates of this week or all the dates of the last seven days in php. Hope it can help friends in need

Get all dates this week:

/**
 * 获取本周所有日期
 */
function get_week($time = '', $format='Y-m-d'){
  $time = $time != '' ? $time : time();
  //获取当前周几
  $week = date('w', $time);
  $date = [];
  for ($i=1; $i<=7; $i++){
    $date[$i] = date($format ,strtotime( &#39;+&#39; . $i-$week .&#39; days&#39;, $time));
  }
  return $date;
}

Execution 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 dates of the last seven days:

/**
 * 获取最近七天所有日期
 */
function get_weeks($time = &#39;&#39;, $format=&#39;Y-m-d&#39;){
  $time = $time != &#39;&#39; ? $time : time();
  //组合数据
  $date = [];
  for ($i=1; $i<=7; $i++){
    $date[$i] = date($format ,strtotime( &#39;+&#39; . $i-7 .&#39; days&#39;, $time));
  }
  return $date;
}

Execution result:

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
)

Summary

The above is the PHP method introduced by the editor to get all the dates of this week or all the dates of the last seven days. I hope it is helpful to you. If you have any questions, please leave me a message and I will reply to you in time. I would also like to thank everyone for your support of the Script House website!

Articles you may be interested in:

Comparison of the effects of php lcg_value and mt_rand generating 0~1 random decimals

How to perform ID prefix formatting class through php

How to restore the data processed by print_r to the original array through php

The above is the detailed content of PHP method to get all dates of this week or all dates of the last seven days. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn