1

I created a function to compare dates:

public function checkExpiredDate($cardDate) : bool
{
     $currentDate = new DateTime();
     $creditCardDate = new DateTime("{$cardDate->card_expiryYear}-{$cardDate->card_expiryMonth}-*last day from the month*");
     echo $creditCardDate->format('Y-m-d'); exit();
     return $creditCardDate->getTimestamp() < $currentDate->getTimestamp() ?? true;
}

I only have the month and year , not the day. I need to compare today's date with that date using only the month and year and the DateTime class . How can I do that ? Is there a way to get the last day from a month and year using the DateTime class? If I could get it someone using DateTime , my function should work .

Attila Naghi
  • 2,535
  • 6
  • 37
  • 59
  • https://stackoverflow.com/questions/1686724/how-to-find-the-last-day-of-the-month-from-date – Frédéric Clausset Nov 10 '17 at 08:41
  • 1
    Hi, would it be an option to use the date() class instead? Why do you need the last day of the month if you only have the month and the year to compare? – Towerss Nov 10 '17 at 08:47

3 Answers3

1

Set day as the 1st day of the month and then modify to the last

$creditCardDate = new DateTime("{$cardDate->card_expiryYear}-{$cardDate->card_expiryMonth}-1");
$creditCardDate->modify('last day of this month');
splash58
  • 26,043
  • 3
  • 22
  • 34
0

Surely it's easier not to use DateTime at all here:

return $cardDate->card_expiryYear . $cardDate->card_expiryMonth <= date('Ym');

This assumes $cardDate->card_expiryYear . $cardDate->card_expiryMonth concatenates to something like 201709; use some number formatting to achieve this format otherwise:

return sprintf('%d%02d', $cardDate->card_expiryYear, $cardDate->card_expiryMonth) <= date('Ym');
deceze
  • 510,633
  • 85
  • 743
  • 889
0

http://php.net/manual/en/datetime.modify.php

$creditCardDate->modify('last day of this month');
Erik
  • 384
  • 1
  • 9