复杂的日期格式

时间:2014-05-04 00:31:12

标签: php arrays date

我正在努力想出最有效和最好的方法来完成这种复杂的情况。我知道我可以使用大约5个if if语句来构建这个解决方案,可能更多 - 但是必须有更好的方法来实现我想要的。

所以这就是我想要做的。我的网站上有一个活动页面,我想做的是尽可能以简约的方式显示日期。我的意思是:

说我有3个日期:May 5May 6May 7。我想将其显示为:May 5 - 7

但是,有些日期可能是:May 5May 7。在这种情况下,我想将其显示为:May 5 & 7

但是,可能还有以下情况:日期可能是:May 25June 2。在这种情况下,我想将其显示为:May 25& June 2

然而!在某些情况下,日期可能是:May 25May 26June 2。在这种情况下,它应显示为:May 25 - 26 & June 2

当然,也可能只有一个日期。但另外一件事,也许有可能会有超过3个日期,所以如果它可以工作而不管有多少日期(IE循环通过数组)会很好。

我知道我们想要尝试并显示一些代码来调试,但是我甚至不知道从哪里开始,如果这对于某些人来说太多了 - 只是让我了解一下如何有效地做这样的事情将是一个巨大的帮助。

由于

1 个答案:

答案 0 :(得分:1)

  //input data: sorted list of dates
  $dates = array('May 5','May 6','May 7','May 30','Jun 2','Jun 3','Dec 11','Dec 12','Dec 14');      
  array_push($dates,false); //add an extra value so the last range gets printed

  //initialize min & previous date as first date
  $min_date = array_shift($dates);
  $prev_date = $min_date; 
  $counter = 0; //keep count of # of days between min and max

  $formatted_dates = array();

  foreach($dates as $date) {
    //if the difference in number of days between current date and min date
    //is greater than counted number of days then we capture the current range
    //and start a new one by resetting $min_date to $date and $counter to 0
    if(!$date || ($counter + 1) < diff_in_days($min_date,$date)) {
      if($counter == 0) { //format for 1 date
        $formatted_dates[] = $min_date;
      } 
      elseif($counter == 1) { //format for 2 dates
        $formatted_dates[] = "$min_date & $prev_date";
      }
      elseif($counter > 1) { //format for > 2 dates
        $formatted_dates[] = "$min_date - $prev_date";
      }

      $counter = 0;
      $min_date = $date;
    } 
    else {
      $counter++;
    }

    $prev_date = $date;
  }

  //may also want to verify that neither formatted date contains an '&'
  //so you don't end up with "May 11 & May 12 & June 1 & June 2" which may be confusing
  if(count($formatted_dates) == 2) {
    print implode(' & ',$formatted_dates);
  }
  else {
    print implode("\n",$formatted_dates);
  }

  function diff_in_days($day1,$day2) {
    $datetime1 = new DateTime($day1);
    $datetime2 = new DateTime($day2);
    $interval = $datetime1->diff($datetime2);
    $ret = (int) $interval->format('%a');
    return $ret;
  }

<强>输出

May 5 - May 7
May 30
Jun 2 & Jun 3
Dec 11 & Dec 12
Dec 14