0

I have 2 dates. One is $monthToCheck = date('Y-m-01'); and the other one comes from an API and its stored in a variable : $reqs['end_date']. My question is : How do i check if the date from the api is bigger than $monthToCheck. With bigger i mean for example 2020 - 01 - 01 is bigger than 2019 - 12 - 01 because the year is higher.

What i tried :

     $time = strtotime($reqs['end_date']);
     $monthToCheck  = date('Y-m-01');
     if($time > $monthToCheck) {...} 

I converted the date from the API to a date using strtotime and then compared it with my $monthToCheck variable.But i have a feeling something isnt right since the results are all "true" eventho that is not always the case.

Kevin.a
  • 4,094
  • 8
  • 46
  • 82

2 Answers2

1

Just put your $monthToCheck into strtotime():

$monthToCheck  = strtotime(date('Y-m-01'));

Example

Aksen P
  • 4,564
  • 3
  • 14
  • 27
0

php can compare dates formatted year-mm-dd easily

if($monthToCheck > $reqs['end_date']){
    // do something
}
Mike Volmar
  • 1,927
  • 1
  • 22
  • 31
  • 2
    Comparing 2 integers is always more reliable than comparing 2 strings representing dates – RiggsFolly Feb 21 '20 at 13:54
  • interesting comment, do you have an example where my technique is less reliable, i'd like to test this – Mike Volmar Feb 21 '20 at 14:00
  • It just stands to reason. Specially as some countries like to put there date in non-logical formats like starting in the middle and working out in one direction or another from there. I speak of the way Americans like to write the dates mm/dd/yyyy :) – RiggsFolly Feb 21 '20 at 14:03
  • 1
    @RiggsFolly that you need to have your date in a proper sortable format for this, is rather a given, I think. That this won’t work with just any arbitrary date format, should be clear to everyone. And considering that the question was about comparing the date part only, timestamps might also give you trouble - when you compare two timestamps that are for the same date, but have different times. Which could rather easily happen as well, if the dates to compare are from different source, and time zone settings might not have been taken into account correctly, or anything like that. – CBroe Feb 21 '20 at 14:07