在PHP中获取给定月份的第一天?

chr*_*ian 3 php date

我一直试图让下面的代码工作,虽然它与6月合作,但它不适用于7月.

对于$ first_day_of_month,下面的结果值为3,周二应为2.

$date = strtotime('20140702'); // July 02, 2014
$month = date('m',$date);
$year = date('Y',$date);
$days_in_month = date('t',$date);
$first_day_of_month = date('w', strtotime($year . $month . 01)); // sunday = 0, saturday = 6
Run Code Online (Sandbox Code Playgroud)

Ale*_*ing 5

strtotime功能支持相对时间格式.你可以这样做:

$date = strtotime('20140702');
$first_date = strtotime('first day of this month', $date);
$first_day_of_month = date('w', $first_date);
Run Code Online (Sandbox Code Playgroud)

第二个参数strtotime提供相对格式相对的时间.您可以使用它来轻松计算相对于特定点的日期,如上所示.