本周包含本月的最后一个星期五


current week contains the last friday of the month

我正在尝试创建一个脚本,如果一个月的最后一个星期五在本周,该脚本将更改页面上的图像。例如,如果我在一周中的任何一天(周一至周日),该天包含该月的最后一个星期五,我将获得与该月其他时间不同的输出。

我在之前的一个问题上得到了这个代码的帮助,但它只有在一个月的最后一天是今天的情况下才有效。然而,我需要函数来知道一个月的最后一天是否在周一、周二、周三、周四,因为我的一周从周一到周日:

// Be sure to check your timezone `date_default_timezone_set`
$today       = new DateTime();
$last_friday = new DateTime('last Friday of this month');
// For testing
$friday_april = new DateTime('2014-4-25');
if ($today->format('Y-m-d') === $last_friday->format('Y-m-d')) {
  print 'Today is friday';
}
if ($friday_april->format('Y-m-d') === $last_friday->format('Y-m-d')) {
  print 'Yes, a test friday is also a friday';
}

任何帮助都会很棒!

更改比较的日期格式。

CCD_ 1就足够了。

为什么

因为那样,同一周内的日期(从周一开始)将产生相同的字符串(ISO周号)。

给定本月,即2014年4月,包含最后一个星期五的一周的周数为17

2014-04-19 Sat => 16 ✗
2014-04-20 Sun => 16 ✗
2014-04-21 Mon => 17 ✓
2014-04-22 Tue => 17 ✓
2014-04-23 Wed => 17 ✓
2014-04-24 Thu => 17 ✓
2014-04-25 Fri => 17 ✓
2014-04-26 Sat => 17 ✓
2014-04-27 Sun => 17 ✓
2014-04-28 Mon => 18 ✗
2014-04-29 Tue => 18 ✗
2014-04-30 Wed => 18 ✗

摘要

if ($today->format('W') === $last_friday->format('W')) {
    // Do victory dance
}

您需要一个循环。通过循环并添加一天,直到进入下个月。计算从今天到下个月初,你遇到了多少个星期五(包括今天)。如果只有1,那么最后一个星期五就是本周。

使用strtotimedate,因此应该如下所示:

$today       = new DateTime();
$last_friday = strtotime('last Friday of this month');
// For testing
$friday_april = new DateTime('2014-4-25');
if ($today->format('Y-m-d') === date('Y-m-d', $last_friday)) {
  print 'Today is friday';
}
if ($friday_april->format('Y-m-d') === date('Y-m-d', $last_friday)) {
  print 'Yes, a test friday is also a friday';
}
$today = getdate();
$weekStartDate = $today['mday'] - $today['wday'];
$weekEndDate = $today['mday'] - $today['wday']+6;
echo "week start date:".$weekStartDate;
echo "<br/>";
echo "week end date:".$weekEndDate;

通过此代码,您可以获得当前一周的开始和结束日期

$thisWeekHasLastFridayOfMonth = function () {
  $lastFridayThisMonth = date('Y-m-d',strtotime('last Friday of this month'));
  $testDate = date('Y-m-d',strtotime('today'));
  $thisWeekSunday = (date('N',strtotime($testDate))!=1?date('Y-m-d',strtotime('last Sunday')):date('Y-m-d'));
  $thisWeekSaturday = (date('N',strtotime($testDate))!=7?date('Y-m-d',strtotime('next Saturday')):date('Y-m-d'));
  //echo $lastFridayThisMonth . '<br>' . $thisWeekSunday . '<br>' . $thisWeekSaturday;
  if (strtotime($lastFridayThisMonth) >= strtotime($thisWeekSunday) &&
          strtotime($lastFridayThisMonth) <= strtotime($thisWeekSaturday))
    return true;
  else
    return false;
};
echo $thisWeekHasLastFridayOfMonth?'True':'False';