Home > Software engineering >  PHP: How to compare months and days( "m-d" dates) with year, month and days ("y-m-d&q
PHP: How to compare months and days( "m-d" dates) with year, month and days ("y-m-d&q

Time:06-25

What is the best way to compare a month and day date ("m-d") with a date with the format "y-m-d".

for example:

$date1 = "2022-04-20";
$date2 = "2022-05-20";

$seasonStart = "03-15";
$seasonEnd = "04-30";

I want to know how many days between $date1 and $date2 are between $seasonStart and $seasonEnd.

CodePudding user response:

You can use DateTime objects for the comparison.

$date1 = new DateTime($date1);
$date2 = new DateTime($date2);

For the seasonal dates, there are a couple of different ways you can do it depending on how you need it to work.

  1. You can use the year from the given date rather than defaulting to the current year, if you want to see if those dates are within the season for the year in which they occur.

    $year = $date1->format('Y');
    $seasonStart = new DateTime("$year-$seasonStart");
    $seasonEnd = new DateTime("$year-$seasonEnd");
    
  2. If you only want to compare the date range to the season for the current year, then you can let the year default to the current one.

    $seasonStart = DateTime::createFromFormat('m-d H:i', "$seasonStart 00:00");
    $seasonEnd = DateTime::createFromFormat('m-d H:i', "$seasonEnd 00:00");
    

Then you can use this to calculate the number of days in the given range that are included in the season.

if ($date1 > $seasonEnd || $date2 < $seasonStart) {
    // in this case the range does not overlap with the season at all
    $days = 0;
} else {
    $days = (max($seasonStart, $date1))->diff(min($seasonEnd, $date2))->days   1;
}

CodePudding user response:

<?php
    $date = DateTime::createFromFormat('m-d', '02-15');
  echo $date->format("Y-m-d");
  $season=$date->getTimeStamp();
  $current=time();
  if ($current>$season) {
    echo "Season has started!";
  }
?>
  • Related