PHP:使用DateTime-Class获取9月的第一天

时间:2015-02-13 10:15:05

标签: php datetime get

使用DateTime-Class时遇到问题。我试着赶上九月的第一天:

$date = DateTime::createFromFormat('Y/d/m', "2014/30/09");

echo "<br />this day: ".$date->format("Y/d/m");

$date->modify('last day of october');
echo "<br />works: first day of october: ".$date->format("Y/d/m");
// Output: 2014/31/10

$date->modify('first day of september');
echo "<br />dont work: first day of september: ".$date->format("Y/d/m");
// Output: 2014/31/10

$date->modify('first day of august');
$date->modify('+1 month');
echo "<br />works: first day of september: ".$date->format("Y/d/m");
// Output: 2014/01/09

有人可以帮助我吗?

我们正在运行:Debian 3.2.63-2上的PHP版本5.4.36-0 + deb7u3 + deb7u2 x86_64

默认时区为:Europe / Berlin

2 个答案:

答案 0 :(得分:0)

如果我们知道第一天将始终表示为1,为什么我们不能使用:

$date->modify('September 1');

使用之前的modify次呼叫时,它会产生所需的输出。

完整代码:

<?php
$date = DateTime::createFromFormat('Y/d/m', "2014/30/09");

echo "<br />this day: ".$date->format("Y/d/m");

$date->modify('last day of october');
echo "<br />works: first day of october: ".$date->format("Y/d/m");

$date->modify('September 1');
echo "<br />dont work: first day of september: ".$date->format("Y/d/m");

$date->modify('first day of august');
$date->modify('+1 month');
echo "<br />works: first day of september: ".$date->format("Y/d/m");

答案 1 :(得分:0)

$new_date = DateTime::createFromFormat('Y/d/m', "2014/15/09");
echo "Date To be changed: ".$new_date->format("Y/d/m");
$new_date->modify('first day of september');
echo "<br><br><b>Changed Date : </b><br> First day of september: ".$new_date->format("Y/d/m");