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):
- get first day of next month
- get next month
- if actual month December, update also year. Otherwise the year remains the same
Part 2 (to):
- get last day of next month of next year
- get next month
- 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?