【问题标题】:Issue with getting week starting from sunday从周日开始获得一周的问题
【发布时间】:2012-10-11 14:14:15
【问题描述】:

以下是我为将星期日作为一周的开始日而创建的函数,


function getCurrentIntervalOfWeek($liveratetime) {
    // get start of each week.
    $dayofweek = date('w', $liveratetime);
    $getdate = date('Y-m-d', $liveratetime);
    $createstart = strtotime('last Sunday', $getdate);
    $weekstart = ($dayofweek == 0) ? $liveratetime : $createstart;
    // get the current time interval for a week, i.e. Sunday 00:00:00 UTC
    $currentInterval = mktime(0,0,0, date('m', $weekstart), date('d', $weekstart), date('Y', $weekstart));
    return $currentInterval;
}

这里的 liveratetime 是一周中任何一天的纪元时间。基本上,这个函数采用 liveratetime 并查找上周日,以获得该 perticulat liveratetime 时期的当前间隔。

但这里的问题是,每当我尝试从中获取当前间隔为某个 liveratetime 时,

$createstart = strtotime('last Sunday', $getdate);
给了我
-345600
。我不明白为什么?谁能分享一下这个。

这通常发生在过去的日期,例如

2007-10-02

【问题讨论】:

    标签: php strtotime


    【解决方案1】:

    您可能想试试这个函数,它会根据提供的日期返回一个日期数组,从星期日开始。

    function get_week_dates( $date )
    {
    // the return array
    $dates = array();
    
    $time = strtotime($date);
    $start = strtotime('last Sunday', $time);
    
    $dates[] = date( 'Y-m-d', $start );
    
    // calculate the rest of the times
    for( $i = 1; $i < 7; $i++ )
    {
        $dates[] = date( 'Y-m-d' , ( $start + ( $i * ( 60 * 60 * 24 ) ) ) );
    }
    
    return $dates;
    }
    

    用法

    get_week_dates( '2011-03-21' );
    

    将返回

    array
      0 => string '2011-03-20' (length=10)
      1 => string '2011-03-21' (length=10)
      2 => string '2011-03-22' (length=10)
      3 => string '2011-03-23' (length=10)
      4 => string '2011-03-24' (length=10)
      5 => string '2011-03-25' (length=10)
      6 => string '2011-03-26' (length=10)
    

    【讨论】:

      【解决方案2】:

      我一直在寻找解决这个问题的方法,经过一些研究和尝试,它似乎可以工作......虽然我仍然需要在下周日进行测试,看看它是否真的有效......无论如何这里是代码:

      $week_start = new DateTime();
      $week = strftime("%U");  //this gets you the week number starting Sunday
      $week_start->setISODate(2012,$week,0); //return the first day of the week with offset 0
      echo $week_start -> format('d-M-Y'); //and just prints with formatting 
      

      【讨论】:

        【解决方案3】:

        Strtotime 的第二个参数是 TIMESTAMP,而不是日期的字符串表示形式。 试试:

        $createstart = strtotime('last Sunday', $liveratetime);
        

        它为您提供 -345600,因为当 $getdate(即 Y-m-d)被解析为 int 时,结果为 0 - 纪元时间。所以,从纪元开始的最后一个星期日就是结果……

        【讨论】:

        • @srahul07 正确阅读了 Bredis 的答案......他正在谈论您对 strtotime 的函数调用。
        猜你喜欢
        • 2022-06-29
        • 2010-11-19
        • 2019-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-14
        • 1970-01-01
        相关资源
        最近更新 更多