Timer.php 1.63 KB
Newer Older
王源's avatar
王源 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
<?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;
    }

}