JoaMika
JoaMika

Reputation: 1827

PHP Get Current year after current month

I am using this code to get current year

echo date("Y");

I also have a variable for the name of the month

$month= "November"

Now it's November and I am getting 2016 which is correct with my code.

However in December, I want to get November 2017 because November 2016 has expired.

How could I go about this?

My code:

<?php the_field('fl_month');echo date("Y"); ?>

Upvotes: 1

Views: 1334

Answers (2)

Marko
Marko

Reputation: 176

// incoming month
$month = 'November';
$monthNumber = date("n", strtotime($month));

// current month
$currentMonth = date("n");

if ($currentMonth >= $monthNumber) {
    echo $month . ' ' . date('Y', strtotime('+1 year'));
} else {
    echo $month . ' ' . date('Y');
}

So I am converting the incoming and current month to number format, checking if current month is bigger or equal than incoming and then based on that, I decide if it should be next year.

Upvotes: 2

WEBjuju
WEBjuju

Reputation: 6581

Loop over each month until you find the next occurrence of November:

$month = 'August';
echo myyear($month); // 2017
$month = 'November';
echo myyear($month); // 2016

function myyear($month) {
  $dt = strtotime($month);
  $target = date('m', $dt);
  if (date('m', time()) == date('m', $dt)) return date('Y');
  do {
    $dt = strtotime('next month', $dt);
  } while ($target != date('m', $dt));
  return date('Y', $dt);
}

Upvotes: 0

Related Questions