我有一个日历类,我只从用户输入年份并生成一年中的所有天数并保存在数据库中。
class Calendar
{
/**
* @var \DateTime
*
* @ORM\Column(name="today_date", type="datetime", nullable=true)
*/
protected $todayDate;
/**
* @var boolean $isBusinessDay
* @ORM\Column(name="is_business_day", type="boolean", nullable=true)
*/
protected $isBusinessDay;
/**
* @var boolean $isHoliday
* @ORM\Column(name="is_holiday", type="boolean", nullable=true)
*/
protected $isHoliday;
/**
* @var time $openTime
*
* @ORM\Column(name="open_time", type="time", nullable=true)
*/
protected $openTime;
/**
* @var time $openTime
*
* @ORM\Column(name="close_time", type="time", nullable=true)
*/
protected $closeTime;
}
if ($form->isSubmitted() && $form->isValid()) {
$weekday = $form["weekday"]->getData();
$start_date = $form["todayDate"]->getData();
$start_date = (string) $start_date->format('Y-m-d');
$start_day = date('z', strtotime($start_date));
$days_in_a_year = date('z', strtotime('2016-12-31'));
$number_of_days = ($days_in_a_year - $start_day) +1 ;
for ($i = 0; $i < $number_of_days; $i++) {
$date = strtotime(date("Y-m-d", strtotime($start_date)) . " +$i day");
print date('d F - l', $date) .'<br />';
if (in_array(date('l', $date), $weekday))
{
print "Match found".'<br />';
$date_temp2 = date('Y-m-d',$date);
print $date_temp2.'<br />';
$date_temp = new \DateTime($date_temp2);
$TodayDate = $date_temp->format('Y-m-d');
$calendar2 = new Calendar();
$calendar2->setTodayDate($TodayDate);
$calendar2->setOpenTime($form["openTime"]->getData());
$calendar2->setCloseTime($form["closeTime"]->getData());
$calendar2->setIsBusinessDay(true);
$calendar2->setIsHoliday(false);
$em->persist($calendar2);
}
else
{
print "Match not found".'<br />';
$calendar2 = new Calendar();
$calendar2->setIsBusinessDay(false);
$calendar2->setIsHoliday(true);
$em->persist($calendar2);
}
}
$em->flush();
}
实际上我只想从用户那里得到年份。获取一年中的第一天并添加一个增量日存储在数据库中。 在 If Block 中,它打印整年的日期。到
30 December - Friday
Match found
2016-12-30
31 December - Saturday
Match not found
最后我得到了这个错误
Error: Call to a member function format() on a non-object
最佳答案
来自 $form['todayDate']
的 $start_date
肯定是 null
。
添加检查以防止此错误。
改变:
$start_date = $form['todayDate'];
收件人:
$start_date = $form['todayDate'] ?: new \DateTime();
像这样,您将当前日期作为 DateTime
对象获取并可以使用 format('Y-m-d')
。
关于php - 错误 : Call to a member function format() on a non-object Generating Each Day of Year,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35332802/