之前PHP项目中利用递归写的一个推算自然月、自然周、自然日的代码
例如(自然周):
上周一00:00:00 到今天晚上周二23:59:59,计算后得到9天
/** * 推算自然月 * 自然月:假如今天1月8号,我要取前2个自然月,则为 12月1号00:00:00 到今天晚上(1月8号)23:59:59 * @param int $naturalMonth 要推算的自然月数 * @param null $time 从哪个时间开始推算 默认当前时间 * @param bool $format 是否要格式化后的时间 默认时间戳 * @return array */ public static function getNaturalMonth($naturalMonth = 2, $time = null, $format = false) { if (empty($time)) { $time = time(); } $naturalMonthArr = []; $currentTime = strtotime(date('Y-m-d 23:59:59', $time)); $currentDay = date("d", $currentTime); // 当前几号 $endTime = $currentTime; $startTime = $endTime - (3600 * 24 * $currentDay); $result = []; if ($naturalMonth > 1) { if ($naturalMonth == 1) { $naturalMonth = 13; } $result = self::getNaturalMonth(--$naturalMonth, $startTime, $format); } if ($format) { $naturalMonthArr[] = [ date("Y-m-d 00:00:00", $startTime + 1), date("Y-m-d 23:59:59", $endTime) ]; } else { $naturalMonthArr[] = [$startTime + 1, $endTime]; } $naturalMonthArr = array_merge($naturalMonthArr, $result); return $naturalMonthArr; } /** * 推算自然周 * 自然周:假如今天周二,我要取前2个自然周,则为 上周周一00:00:00 到今天晚上(周二)23:59:59 总计7+2 = 9天 * @param int $naturalWeek 要推算的自然周数 * @param null $time 从哪个时间开始推算 默认当前时间 * @param bool $format 是否要格式化后的时间 默认时间戳 * @return array */ public static function getNaturalWeek($naturalWeek = 5, $time = null, $format = false) { if (empty($time)) { $time = time(); } $naturalWeekArr = []; $weekArr = [7, 1, 2, 3, 4, 5, 6]; $currentTime = strtotime(date('Y-m-d 23:59:59', $time)); $currentWeek = $weekArr[date("w", $currentTime)]; $endTime = $currentTime; $startTime = $endTime - (3600 * 24 * $currentWeek); $result = []; if ($naturalWeek > 1) { $result = self::getNaturalWeek(--$naturalWeek, $startTime, $format); } if ($format) { $naturalWeekArr[] = [ date("Y-m-d 00:00:00", $startTime + 1), date("Y-m-d 23:59:59", $endTime) ]; } else { $naturalWeekArr[] = [$startTime + 1, $endTime]; } $naturalWeekArr = array_merge($naturalWeekArr, $result); return $naturalWeekArr; } /** * 推算自然日 * @param int $naturalDay * @param null $todayTime * @param bool $format * @return array */ public static function getNaturalDay($naturalDay = 6, $todayTime = null, $format = false) { if (empty($todayTime)) { $todayTime = time(); } $naturalDayArr = []; for ($i = $naturalDay; $i >= 0; $i--) { if($format){ $startTime = date('Y-m-d 00:00:00', $todayTime - (86400 * $i)); $endTime = date('Y-m-d 23:59:59', $todayTime - (86400 * $i)); }else{ $startTime = strtotime(date('Y-m-d 00:00:00', $todayTime - (86400 * $i))); $endTime = strtotime(date('Y-m-d 23:59:59', $todayTime - (86400 * $i))); } $naturalDayArr[] = [$startTime, $endTime]; } return $naturalDayArr; }
评论前必须登录!
注册