Support

Account

Home Forums General Issues Comparing Two Date Fields and Using an if Statement

Solved

Comparing Two Date Fields and Using an if Statement

  • Hello there. I had question. I’m building a project for events that has two date fields (Start and End dates). I figured out how to manipulate the date formatting for the two fields so it displays it like this: July 12-16, 2020.

    That works great except if the start and end dates cross over into a different month.

    Start: July 12
    End date: August 3

    It outputs it as July 12-3, 2020. How can I fix it so that if the second field is a different month then to display that month?

    Ideally the output would be July 12-13 if the months are the same and July 12-August 3, 2020 if the months are different.

    Here is my sample code:

    $start_date = get_field('trip_start_date', false, false);
    $start_date = new DateTime($start_date);
    $end_date = get_field('trip_end_date', false, false);
    $end_date = new DateTime($end_date);
    ?>
    
    <?php echo $start_date->format('F j'); ?>-<?php echo $end_date->format('j, Y'); ?>
  • You need to compare the different parts. Something line this, I don’t know the exact code here so getting the month in each case is just a guess on my part.

    
    $start_month = $start_date->format('F');
    $end_month = $end_date->format('F');
    if ($start_month == $end_month)) {
      // output July 12-13, 2020
    } else {
      // output July 12 - August 3, 2020
    }
    

    I would probably also make this more complicated, comparing years as well because you might have an event that goes from Dec of one year into Jan of the next.

    
    if ($start_year == $end_year) {
      if ($start_month == $end_month) {
        // output July 12-13, 2020
      } else {
        // output July 12 - August 3, 2020
      }
    } else {
      // output Dec 30, 2019 - Jan 3, 2020
    }
    
  • Wow, thanks so much for the code suggestion. This sets me in the right direction. I hadn’t thought about accommodating for years as well.

    Thanks again.

  • Actually, neither did I, after this I went and updated a site that was going to break soon. I have something similar that has month, day and time (date/time picker). I didn’t account for changing years either 😛

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.