简体   繁体   中英

PHP: year when a date occurs the next time

I need a function that returns the year when a given date (day + month) occurs the first time from now on.

function year($day, $month) {
  // ...
  return $year;
}

$day and $year are two-digit numbers

Eg the given date is '12/25' it should return '2016' (or '16'), but if the date is '02/25' it should return '2017' (or '17'). [Today is August 30, 2016]

Leap years may be disregarded and input doesn't have to be validated.

EDIT: My attempt

year($day, $month) {

  $today_day = date('d');
  $today_month = date('m');

  $year = date('y');

  if($month > $today_month) {
    return $year;
  } else if ($month < $today_month) {
    return $year + 1;
  } else {
    if($day >= $today_day) {
      return $year;
    } else {
      return $year + 1;
    }
  }

}

Just compare the date you are checking against today. If it is today or earlier increment the year of the date. Otherwise do not. Then return that year.

DateTime() functionality makes this easy to do.

function year($day, $month) {
  $date  = new DateTime("{$month}/{$day}"); // defaults to current year
  $today = new DateTime();
  if ($date <= $today) {
      $today->modify('+1 year');
  }

  return $today->format('Y');
}

echo year(6, 6); // 2017
echo year(12, 12); // 2016

Demo

I appreciate your effort! It was pretty good, but can certainly use some fine tuning. We could reduce the no. of unnecessary if statements.

The function accepts two parameters: month and date. Please be sure we follow the order while calling the function.

In the function, $date is the input date concatenated with the current year.

Eg: year(12,25) refers to the year where month is December (12) and day is 25.

year(12,25) would make $date as 2015-12-25.

 function year($month, $day) 
 { 
     $date= date('Y').'-'.$month.'-'.$day;
     if (strtotime($date) > time()) {
         return date('y');
     }
     return (date('y')+1);
 }

 echo year(12,25);   // 16

 echo year(2,25);    // 17

Now, all we need to do is check the timestamp of $date with the current timestamp- time() .

strtotime($date) > time() input date timestamp is more than current timestamp. Which implies this date is yet to come in this year. So, we return the current year date('Y').

If the above if is not executed, it's obvious that this date has passed. Hence we return the next year date('Y') + 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM