1

I have written a code in php to show amazon sale banner on my site for a specific date range when amazon sales become live any time and i set that date range. Following is the code, but my problem is that, the if condition is working on the particular date range every month, whereas I want it to work only in that particular month for which I have specified in date range of that particular month. Please check where I am wrong in the code, please help.

  $start_date = "01-10-2021";
    $end_date = "07-10-2021";
    
    $now = new DateTime();
    $now = $now->format( 'd-m-Y' );
    
    $startdate = new DateTime($start_date);
    $startdate = $startdate->format( 'd-m-Y' );
    
    $enddate = new DateTime($end_date);
    $enddate = $enddate->format( 'd-m-Y' );
    
        if($startdate <= $now && $now <= $enddate) {
            $show_amazon_discount = 1;
            } else {
               $show_amazon_discount = 0; }

This code returns $show_amazon_discount = 1 every month between 1st to 7th date, but I need it to retrun true only on 01 oct to 7oct 2021 only and not for every month. Please help where I am wrong, whats mistake in my code. thanks in advance.

user43724
  • 11
  • 3
  • 3
    When you call `format()` on a date object, you are converting it to a string, which causes a string comparison to happen later, not a date one. Don’t call `format()` unless you need to display it, keep the dates as objects for the comparison. Also, your variables are dangerously similar in naming, `startdate` and `start_date`, which is asking for trouble some day in the future. Not wrong, just easily confusable. – Chris Haas Jan 02 '22 at 15:27
  • Thanks, can you please extend little more help, please write what how exactly I should compare the dates object, please help with code. thanks – user43724 Jan 02 '22 at 16:35
  • Does this answer your question? [PHP check if date between two dates](https://stackoverflow.com/questions/19070116/php-check-if-date-between-two-dates) – M. Eriksson Jan 02 '22 at 17:20

0 Answers0