Php DateTime::createFromFormat未按预期工作?
我正在编写一个php脚本,如下所示:Php DateTime::createFromFormat未按预期工作?,php,Php,我正在编写一个php脚本,如下所示: December 2020 2020-12-01 2020-12-31 January 2021 2021-01-01 2021-01-31 Febuary 2021 2021-02-01 2021-02-28 March 2021 2021-03-01 2021-03-31 基本上显示从最开始到最后一个月的日期。但我在执行时出错了 Fatal error: Call to a member function format() on boolean
December 2020
2020-12-01
2020-12-31
January 2021
2021-01-01
2021-01-31
Febuary 2021
2021-02-01
2021-02-28
March 2021
2021-03-01
2021-03-31
基本上显示从最开始到最后一个月的日期。但我在执行时出错了
Fatal error: Call to a member function format() on boolean
根据我的理解,DateTime::createFromFormat应该将基于给定格式的任何字符串解析为date()上可以找到的另一种格式,但我遇到了错误,我尝试了旧方法,如使用date(“Y-m-01”,strotime($month))
但php输出1970-01-01
和1970-01-31
我的代码:
$veryfirstmonth = "2020-12-01 18:01:15";
$veryfirstmonth = date('Y-m-d', strtotime($veryfirstmonth));
$today = date("Y-m-d");
$start = (new DateTime($veryfirstmonth))->modify('first day of this month');
$end = (new DateTime($today))->modify('first day of this month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $month = $dt->format("F Y") . "<br>\n";
//Convert $month into start of month and end of month again
// echo $start = date("Y-m-01", strtotime($month));
// echo $end = date("Y-m-t", strtotime($month));
$start = DateTime::createFromFormat("F Y", $month)->format("Y-m-01");
$end = DateTime::createFromFormat("F Y", $month)->format("Y-m-t");
echo "Start: " . $start . "\n";
echo "End: " . $end . "\n\n";
}
$veryfirstmonth=“2020-12-01 18:01:15”;
$veryfirstmonth=日期('Y-m-d',标准时间($veryfirstmonth));
$today=日期(“Y-m-d”);
$start=(新的日期时间($veryfirstmonth))->modify($本月的第一天);
$end=(新的日期时间($today))->modify($本月的第一天);
$interval=DateInterval::createFromDateString('1个月');
$period=newdateperiod($start、$interval、$end);
foreach(期间为$dt){
echo$month=$dt->format(“fy”)。“
\n”;
//将$month再次转换为月初和月底
//echo$start=日期(“Y-m-01”,标准时间($month));
//echo$end=日期(“Y-m-t”,标准时间($month));
$start=DateTime::createFromFormat(“fy”,$month)->格式(“Y-m-01”);
$end=DateTime::createFromFormat(“fy”,$month)->格式(“Y-m-t”);
回显“开始:.$Start.\n”;
echo“End:.$End.\n\n”;
}
您的代码与我一起工作只需删除“
\n”
替换该行即可
echo $month = $dt->format("F Y") . "<br>\n";
不客气
echo $month = $dt->format("F Y");
echo "\n";