PHP |如何查找本年度第二个星期日至下一个星期日的每个星期日

时间:2015-01-28 09:47:16

标签: php date mktime

背景:我的客户,一个本地电影院,每隔一个星期天开始一个星期日Matinee特别节目,从每年的第二个星期日开始。所以今年的日期分别是1 / 11,1 / 18,2 / 8,2 / 22 ...... [唯一的例外是他们的电影节之后的星期日,这个节日将持续到10月的第三个星期,但是自动化这个例外是一个很好的"项目,不是必需的。]

MY SKILL LEVEL:BEGINNER(我需要你的帮助!)我相信我需要使用mktime()和date()的组合,但我不知道如何将它组合在一起。

我做了什么:我怀疑答案是我在这三个帖子上看到的结合:

(1)a do-while loop to get a specific day of the week from a date range

(2)there may be a shortcut for referencing the second sunday in the ACCEPTED ANSWER here, but I'm not sure this helps

(3)MOST RELEVANT(?): Get the First Sunday of Every Month

结束结果:我想显示下周日Matinee的[月]和[日](所以我想在当前日期之后找到并显示数组中的第一项)。文本将如下所示:"下一个:[月] [日]"

有意义吗?如果我忘了什么,请告诉我。

如果问题不是太多,请解释一下你的代码,以便我(以及其他人)可以从中学习;但我不仅仅感谢#34;而且#34;一个直接的解决方案。

非常感谢。 德布拉

更新/进展:此代码将为我提供星期日阵列:

$startDate = strtotime("second Sunday of ".date('Y').""); for ($i=0; $i < 27; $i++){ $sundays = date('F j', ($startDate + (($i*14) * 24 * 3600))) . '<br>'; print $sundays; }

下一步:写出一个声明,在周日数组中查找当前日期之后的第一个日期。

1 个答案:

答案 0 :(得分:0)

这是一个非常手动的程序解决方案,但它应该可行。

<?php
$SECS_PER_DAY = 86400;

# Find the first Sunday on or after a given timestamp
function firstSundayOnOrAfter($time) {
  global $SECS_PER_DAY;

  # What day of the week is the given date?
  $wday = date('w', $time);

  if ($wday == 0) {
    # it's already a Sunday
    return $time;
  } 

  return $time + (7 - $wday) * $SECS_PER_DAY;
}

# return an array of timestamps representing 
# (noon on) the special matinee Sundays for the given year
function specialMatineeSundays($year) {

  global $SECS_PER_DAY;

  # When's the film festival?
  $oct1 = mktime(12,0,0,10,1,$year);
  $festivalStart = firstSundayOnOrAfter($oct1);
  $festivalSkip  = $festivalStart + 7 * $SECS_PER_DAY;

  # find the first Sunday of the year
  $jan1 = mktime(12,0,0,1,1,$year);
  $sunday = firstSundayOnOrAfter($jan1);

  # Add a week to start with the second Sunday
  $sunday += 7 * $SECS_PER_DAY;

  # Build up our result list
  $result = [];

  # As long as the Sunday under examination is still the same year, 
  # add it to the list (unless it's the post-festival skip date)
  # and then add two weeks 
  while (date('Y',$sunday) == $year) {
    if ($sunday != $festivalSkip) {
      $result[] = $sunday;
    }
    $sunday += 14 * $SECS_PER_DAY;
  }

  return $result;
}