dousu5608
2016-06-11 16:40
浏览 37

PHP如何从Unix时间戳中提取一个月的第一天

There is this Unix timestamp and it needs to generate the first days of the week as an array.

    $time = '1456034400'; 
    // This present Month February 2016
    // in calendar the February has the start of the week 
    // Sunday 7
    // Sunday 14
    // Sunday 21
    // Sunday 28

How do you get an array like this from the Unix Timestamp:

    $weekdays = array(
                  0 => 7,
                  1 => 14,
                  2 => 21,
                  3 => 28
                 );

And this method needs to work and be accurate for any given month in years not just Feb 2016.

图片转代码服务由CSDN问答提供 功能建议

有这个Unix时间戳,它需要以数组的形式生成一周的前几天。

  $ time ='1456034400';  
 //本月二月2016 
 //在日历中,二月有一周的开始
 //星期日7 
 //星期日14 
 //星期日21 
 //星期日28 
 <  / code>  
 
 

如何从Unix时间戳中获取这样的数组:

  $ weekdays = array(
 0 =  &gt; 7,
 1 =&gt; 14,
 2 =&gt; 21,
 3 =&gt; 28 
); 
   
 
 

这个 方法需要工作,并且在2016年2月的任何特定月份都要准确。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyuedaochen8415 2016-06-11 17:00
    已采纳
    function getSundays($y, $m)
    {
        return new DatePeriod(
            new DateTime("first Sunday of $y-$m"),
            DateInterval::createFromDateString('next sunday'),
            new DateTime("last day of $y-$m")
        );
    }
    
    
    $days="";
    foreach (getSundays(2016, 04) as $Sunday) {
        $days[] = $Sunday->format("d");
    }
    
    var_dump($days);
    

    https://3v4l.org/DVYM5

    已采纳该答案
    打赏 评论
  • dsnnvpobaljihv3490 2016-06-11 18:14

    A bit faster way (since it uses a simple calculation to iterate weeks):

    $time = 1456034400;
    
    $firstDay = strtotime('first Sunday of '.date('M',$time).' '.date('Y',$time));
    $lastDay =  mktime(0,0,0,date('m',$time)+1,1,date('Y', $time));
    
    $weekdays = array();
    
    for ($i = $firstDay; $i < $lastDay; $i += 7*24*3600){
        $weekdays[] = date('d',$i);
    }
    

    https://3v4l.org/lQkB2/perf#tabs

    打赏 评论

相关推荐 更多相似问题