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

时间:2014-04-24 18:45:27

标签: php

我正在尝试创建一个脚本,如果当月的最后一个星期五是在当前周,则会更改页面上的图像。例如,如果我在一周中的任何一天(星期一到星期日)中包含该星期的最后一个星期五,那么我将获得与该月剩余时间不同的输出。

我在上一个问题中使用此代码获得了帮助,但只有在当月的最后一天才能使用。但是我需要这个函数来知道一个月的最后一天是星期一,星期二,星期三,星期四仍然是当周,因为我的星期从星期一到星期日:

// 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';
}

任何帮助都会很棒!

5 个答案:

答案 0 :(得分:5)

更改比较的日期格式。

W就足够了。

为什么?!

因为那时将在同一周(从星期一开始)的日期生成相同的字符串(ISO week number)。

鉴于本月,即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 :(得分:0)

你需要一个循环。完成循环并添加一天,直到下个月。计算从今天到下个月开始你遇到的星期五(包括今天)。如果它只有1,那么最后一个星期五是在本周。

答案 2 :(得分:0)

使用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';
}

答案 3 :(得分:0)

$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;

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

答案 4 :(得分:0)

$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';
相关问题