【问题标题】:Calculate PHP difference between a date and a day of a month计算日期和一个月中某天之间的 PHP 差异
【发布时间】:2014-03-03 02:35:51
【问题描述】:

我正在研究 php 函数,该函数根据一些变量进行数学运算以获取一年中的周数。

其实我有2个变量:

  1. first 是一个日期变量(格式为 YYYY-MM-DD);
  2. second 是一个“day-mark”变量(我有一个包含 9 个特定日期的列表 -> 2、6、8、10、14、17、21、23、27);

这是我设法组合的函数,以便我可以获取一年中的星期:

$duedt = explode("-", "YYYY-MM-DD");
$date = mktime(0, 0, 0, $duedt[1], $duedt[2], $duedt[0]);
$week = (int)date('W', $date); 

以上述代码为例,如果我们将“YYYY-MM-DD”替换为“2014-02-09”,则判断周数为6(女巫是正确的)

现在,我的问题是:如何修改它,以便跟踪第二个变量(“日标记”)

对于“2014-02-09”天的例子,我想要的是以下内容:

  • 如果“day-mark”是 10(表示每月的 10 号)=> 星期 数字将是 7
  • 如果“day-mark”是 8(表示第 8 月) => 周数为 6

关于如何修改函数的任何想法?

提前谢谢你!

我最好的问候, 迈克尔

【问题讨论】:

    标签: php date datetime days


    【解决方案1】:

    我不确定您是否过于复杂。您不能只提供日期并使用相同的方法获取任何日期的周数吗?或者更简单:

    $date = new DateTime('2014-02-08');
    echo (int) $date->format('W'); // 6
    
    $date = new DateTime('2014-02-09');
    echo (int) $date->format('W'); // 6
    
    $date = new DateTime('2014-02-10');
    echo (int) $date->format('W'); // 7
    

    【讨论】:

    • 约翰您好,感谢您提供代码。事实上,这个想法有点“看起来过于复杂”,但本质上它很简单 :) 实际上,找出这段代码中的星期数是多少,将有助于打开带有数据的特定 excel 电子表格 :) 这就是我需要这两个变量的原因!再次感谢您的代码,但这不是我想要实现的......
    【解决方案2】:
    function week_day_of_month($day,$month_num, $year) {
      $days_in_month = array(1=>31, 2 => 28,...);//doesn't account for leap, you need to
      $ts = strtotime(format_date($day,$month_num,$year));
      $week_num = date('W', $ts);
      $month_days = $days_in_month[$month_num];
      for ($i = 1;$i<=$month_days;$i++) {
        $ats = strtotime(format_date($i,$month_num, $year));
        if ($ats == $ts)
        break;
      }
     $day = $i;
     return array($day,intval($week_num));
    }
    

    format_date 只是将 m,d,y 转换为 strtotime 可以解析的内容。 您可以通过在月份 0=> 非闰,1=> 闰的几天内拥有两个数组来处理闰。计算跳跃很容易。并选择正确的数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-09
      • 2019-12-27
      • 2011-05-16
      • 1970-01-01
      • 2023-01-31
      • 2010-12-04
      • 2010-11-07
      相关资源
      最近更新 更多