Commit 85d38a53 authored by 王源's avatar 王源 🎧

添加时间工具类

parent f68443a3
<?php
/**
* Created by PhpStorm.
* User: Zero
* Time: 2020/11/19 15:35
*/
namespace Meibuyu\Micro\Tools;
class Timer
{
/**
* 获取时间区间
* @param int $num 正数为向后取时间,负数为向前取时间
* @param string $type 支持 year month day hour minute second
* @param string $begin 开始时间,默认此时此刻
* @param string $format
* @return array
* @author Zero
*/
public static function getRange(int $num, string $type, string $begin = null, string $format = null)
{
switch ($type) {
case 'year':
!$format && $format = 'Y';
break;
case 'month':
!$format && $format = 'Y-m';
break;
case 'day':
!$format && $format = 'Y-m-d';
break;
case 'hour':
!$format && $format = 'Y-m-d H';
break;
case 'minute':
!$format && $format = 'Y-m-d H:i';
break;
case 'second':
!$format && $format = 'Y-m-d H:i:s';
break;
}
$timeStr = $type . 's';
$begin = $begin ? strtotime($begin) : time();
$end = strtotime("+{$num} {$timeStr}", $begin);
if ($begin > $end) { // 如果开始时间比结束时间大,则反转
$temp = $begin;
$begin = $end;
$end = $temp;
}
$data = [];
while ($begin <= $end) {
$data[] = date($format, $begin);
$begin = strtotime("+1 {$timeStr}", $begin);
}
return $data;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment