【问题标题】:How many, of a given weekday there has been since the beginning of this month?自本月初以来,有多少个给定的工作日?
【发布时间】:2013-08-14 10:54:15
【问题描述】:

我有一个约会,我想知道这个工作日有多少,从本月初开始。 (应该是 1-5)

我需要这个号码的原因是因为我告诉客户我将在“每月的第四个星期三”交付一些东西。

我不需要只返回从预定义的一周开始日期开始的周数(我能找到的每个示例都这样做)。

知道我已经按如下方式实现了这段代码的反面,这可能会有所帮助:

echo date('Y-m-d', strtotime("2013-08 4 Wednesday")); 
//returns the 4th Wednesday of the month namely "2013-08-28"

如何获得以“2013-08-28”开头的“4”?

【问题讨论】:

  • 哦,加油!!你有没有费心去查看 date() 的手册?
  • 那是 "星期三" 而不是 Wedneday ;-)

标签: php date strtotime


【解决方案1】:

或者,或者...

function getHowManyOfWeekday($d) { 
  $g = getdate($d);
  return ceil($g['mday'] / 7) + 1;
}

// Some tests ... 
echo getHowManyOfWeekday(strtotime("2013-08-07")). "\n";
echo getHowManyOfWeekday(strtotime("2013-08-11")). "\n";
echo getHowManyOfWeekday(strtotime("2013-08-18")). "\n";
echo getHowManyOfWeekday(strtotime("2013-08-19")). "\n";
echo getHowManyOfWeekday(strtotime("2013-08-31")). "\n";

【讨论】:

    【解决方案2】:

    这样的表达式只需对您的代码进行最少的更改即可工作。

    <?php
    $d = date('d', strtotime("2013-08-28")); 
    echo ceil($d/7).PHP_EOL;
    ?>
    

    输出“4”。我相信你可以将它包装在一个函数中。

    ceil()

    【讨论】:

    • 或者date('w', $time) + 1 怎么样?!
    • @onetrickpony:错字? echo date('w', strtotime('2013-12-28'))+1; 输出 7。
    • 从逻辑上讲,这比我想象的要容易得多。感谢您的快速响应
    【解决方案3】:

    我将对此进行破解...我认为如果您将 PHP date() 函数返回的月份数除以 7 和 ceil(),它会为您提供正确的数字(我只是与我的日历相比,所以不是 100% 有保证)。以下代码包含一个函数并在最后运行一个测试循环,产生以下输出

    每月的第二个星期一
    本月第二个星期二
    本月的第二个星期三
    每月第三个星期四
    本月第三个星期五
    本月第三个星期六
    本月第三个太阳
    每月第三个星期一
    本月第三个星期二
    本月第三个星期三
    每月第四个星期四
    本月第四个星期五
    本月第四个星期六
    本月第四个太阳
    每月的第四个星期一
    每个月的第四个星期二

    <?php
    
       function getDateString($time) {
         date_default_timezone_set ( "America/Los_Angeles" );
         //$time = time();
         $which_day = ceil((int) date('j', $time) / 7);
         $which_day_name = date('D', $time);
    
         $suffix = 'st';
         switch ($which_day) {
           case 2 : 
             $suffix = 'nd';
             break;
           case 3 :
           case 4 :
           case 5 :
             $suffix = 'th';
             break;
         }   
    
         return $which_day . $suffix . ' ' . $which_day_name . ' of the month ' . PHP_EOL;
       }
    
    
       $time = time();
       echo getDateString($time);
       foreach (range(0, 15) as $day) {
         $time = time() + ($day * 24 * 60 * 60);
         echo getDateString($time);
       }
     ?>
    

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 2017-10-07
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多