简体   繁体   English

PHP如何从Unix时间戳中每月提取一周的前几天

[英]PHP How to extract first days of the weeks from a Month from Unix timestamp

There is this Unix timestamp and it needs to generate the first days of the week as an array. 有这个Unix时间戳,它需要将一周的第一天作为数组生成。

    $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: 您如何从Unix时间戳记中获得这样的数组:

    $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. 而且这种方法需要有效并且在数年内任何给定月份(不仅是2016年2月)中都是准确的。

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 https://3v4l.org/DVYM5

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 https://3v4l.org/lQkB2/perf#tabs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM