首页 > 解决方案 > 如何根据当前日期生成一年期?

问题描述

我想根据当前日期生成一个期间。

例如:

我的方式:

第 1 部分(来自):

  1. 得到下个月的第一天
  2. 下个月拿到
  3. 如果实际是 12 月,也更新年份。否则年份保持不变

第 2 部分(至):

  1. 获取明年下个月的最后一天
  2. 下个月拿到
  3. 更新年份

我的代码:

function createLicenceDate($orderDate){

    //Part 1: First part of period => 01 Apr 2020

    //remove time (is not necessary)
    $explodeOnlyDate = explode(" ", $orderDate);

    //get date
    $onlyDate = $explodeOnlyDate[0];

    //seperate day, month and year
    $explodeDate = explode("-", $onlyDate);

    //First day of next month
    $newDay = 01;

    //check if actual date is december. If true = update also the year
    if($explodeDate[1] != 12){
        //update month
        $newMonth = $explodeDate[1] + 1;
        //year remains the same
        $year = $explodeDate[0];
    }else{
        //new month is january
        $newMonth = 1;
        //update year
        $year = $explodeDate[0] + 1;
    }

    //date as string
    $fromString =  $newDay.'-'.$newMonth.'-'.$year;
    //convert string to date
    $from = date('d M Y', strtotime($fromString));

    //Part 2: Second part of period => 31 Mar 2020

    //update year
    $untilNewYear = $explodeDate[0] + 1;

    //get last day of next month by getting amount of days of a month of a year
    $untilNewDay = cal_days_in_month(CAL_GREGORIAN, $explodeDate[1], $untilNewYear);

    //the month always remains unchanged 
    $untilNewMonth = $explodeDate[1];

    //date as string
    $untilString = $untilNewDay."-".$untilNewMonth."-".$untilNewYear;

    //string as date
    $until = date('d M Y', strtotime($untilString));

    $licenseValidationDates [] = $from;
    $licenseValidationDates [] = $until;

    return $licenseValidationDates;

}

我的代码有效。但我确信这不是最好/最有效的解决方案。我决定这样做是因为我在 php 的替代方案和日期函数方面遇到了很多问题。我尤其遇到闰年和二月的问题。从日期到字符串的转换以及反之亦然是另一个问题。

你能提出一个“更好”的解决方案吗?我的方法是不是太麻烦了?

标签: phptimeperiod

解决方案


推荐阅读