需要PHP 5.3才能工作(PHP 5.3中引入了“第一天”)。否则,上面的示例是唯一的方法:
// First day of this month
$d = new DateTime('first day of this month');
echo $d->format('jS, F Y');
// First day of a specific month
$d = new DateTime('2010-01-19');
$d->modify('first day of this month');
echo $d->format('jS, F Y');
// alternatively...
echo date_create('2010-01-19')
->modify('first day of this month')
->format('jS, F Y');
在PHP 5.4+中,您可以执行以下操作:
// First day of this month
echo (new DateTime('first day of this month'))->format('jS, F Y');
echo (new DateTime('2010-01-19'))
->modify('first day of this month')
->format('jS, F Y');
如果您希望使用简洁的方式执行此操作,并且已经有年份和月份的数值,则可以使用date():
echo date('Y-m-01'); // first day of this month
echo date("$year-$month-01"); // first day of a month chosen by you