0

I want to generate a period based on the current date.

For Example:

  • Input: 2020-03-10 08:54:23
  • Output: 01 Apr 2020 - 31 Mar 2020

My way:

Part 1 (from):

  1. get first day of next month
  2. get next month
  3. if actual month December, update also year. Otherwise the year remains the same

Part 2 (to):

  1. get last day of next month of next year
  2. get next month
  3. update year

My Code:

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;

}

My code works. But I'm sure this is not the best/most efficient solution. I decided to go this way because i had many problems with alternatives and date functions of php. I especially had problems with leap years and February. The conversion from date to string and vice versa was another problem.

Can you suggest a "better" solution? Is my way too much trouble?

Cello
  • 31
  • 1
  • 1
  • 7
  • PHP can do all that for you. Read up on [DateTimeImmutable](https://www.php.net/manual/en/class.datetimeimmutable). Also, this might be more fitting for https://codereview.stackexchange.com/, since you have a working solution. – El_Vanja Mar 10 '20 at 09:09
  • https://www.php.net/manual/en/class.dateperiod.php – Yahya Ayyoub Mar 10 '20 at 09:28

0 Answers0