一年一个月的一周?

时间:2011-05-25 12:31:33

标签: php datetime math calendar

我正在尝试将一年中的一个月的数量除以一年中一周的数量。 所以例如第1周是在1月,并且返回1,第6周是在2月,所以我想要2。

我尝试使用date_parse_from_format('W/Y'),但没有成功(它给了我错误)。

有没有办法使用date_parse_from_format()或有其他方法吗?

4 个答案:

答案 0 :(得分:6)

print date("m",strtotime("2011-W6-1"));

(注意到在2011年,1月有六周,因此第6周(根据某些定义)是在第1个月。)

答案 1 :(得分:2)

只想为第一个答案添加一个注释,第1周到第9周的周数应为01-09(如果不添加前导零,它将始终给出第1个月)

date("m",strtotime("2011-W06-1"));

答案 2 :(得分:2)

使用PHP DateTime对象(这是处理日期的首选方式,请参阅下面的链接以获取更多信息),您可以这样做:

$dateTime = new \DateTime();
$dateTime->setISODate($year,$week);
$month = $dateTime->format('n');

请注意,以下内容不适用于周" W"是not a supported format

$month = \DateTime::createFromFormat("W/Y ", "1/2015")->format('n');

此方法使用的格式is the same supported by the function您尝试使用date_parse_from_format,因此错误。

答案 3 :(得分:1)

像这样的东西会做,这也经过测试并起作用:

function getMonthByNumber($number,$year)
{
    return date("F",strtotime('+ '.$number.' weeks', mktime(0,0,0,1,1,$year,-1)));
}

echo getMonthByNumber(27,2011);

希望这有帮助

相关问题