鬼一浪人 2019-09-02 15:26:56 4093次浏览 2条评论 0 0 0
/**
 * 获取当前时间过去12个月的梯阶,含当月;
 * @author 鬼一浪人
 * @date 2019-09-02
 * @param  string $date 默认当前时间,可传入Y-m-d,或其他允许的日期格式
 * $param  string $timezone
 * @return [type]       [description]
 */
function getDateYmPeriod($date = 'now', $timezone = 'PRC')
{
    $timezone = new DateTimeZone($timezone);
    //以此作为基准
    $date = new DateTime($date,$timezone);

    $startDate  = new DateTime($date->format('Y-m'), $timezone);
    //28每个月都有,不会出现月末转月头的计算差异;若是为1,则有该问题
    //若不想含当月,可将28设置成1,且下文的P11M改成P12M,如此即可;
    $endDate = new DateTime($date->format('Y-m-28'), $timezone);

    //在当前时间减去12个月,做为开始时间,起始月算第一个
    $startDate->sub(new DateInterval('P11M'));

    //格式化成月梯阶
    $date_ranage = new DatePeriod($startDate, new DateInterval('P1M'), $endDate);

    $return = [];
    foreach ($date_ranage as $key => $date) {
        $return[] = $date->format('Y-m');
    }
    return $return;
}
  • 评论于 2019-11-18 13:13 举报
    function getPeriod($date="now", $num=12)
     {
         $time = strtotime($date);
         $return = [];
         for($i=0;$i<$num;$i++) {
             $return[] = date("Y-m", strtotime("-${i} month", $time));
         }
         return $return;
    }
    
  • 评论于 2019-09-02 17:29 举报

    牛逼了,写的代码我都看不懂了

您需要登录后才可以评论。登录 | 立即注册