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

时间:2016-06-11 16:40:35

标签: php unix

有这个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

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

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

这种方法需要在2016年2月的任何特定月份都能正常工作。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

更快一点的方法(因为它使用简单的计算来迭代几周):

$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