Home > Enterprise >  PHP Fatal error: Call to a member function format() on string
PHP Fatal error: Call to a member function format() on string

Time:10-06

I am trying to save dates to an SQL-database using Doctrine. The user writes the dates to input-fields using datepicker and they have the format dd.mm.yyyy (german). In the database the dates look like this "2021-09-30" or this "0000-00-00" if no date is given

I am using this code to set the Input data to the entity:

if(isset($formData["startDate"]) and $formData["startDate"] != "") {
    $sD = explode(".", $formData["startDate"]);
    $campaign->setStartDate(($sD[2]."-".$sD[1]."-".$sD[0]));
} else {
    $campaign->setStartDate("0000-00-00")
}

But this produces the error Fatal error: Call to a member function format() on string. How can i save the dates to my database?

Here are the field and getter/setter:

/**
 * @ORM\Column(type="date")
 */
protected $startDate;



/**
 * Set startDate
 *
 * @param integer $startDate
 * @return Campaign
 */
public function setStartDate($startDate)
{
    $this->startDate = $startDate;

    return $this;
}

/**
 * Get startDate
 *
 * @return integer
 */
public function getStartDate()
{
    return $this->startDate;
}

CodePudding user response:

First of all, you can define your setter/getter with \DateTimeInterface, like this

/**
 * @ORM\Column(type="datetime", options={"default":"0000-00-00 00:00:00"})
 */
 protected $startDate;

/**
 * Set startDate
 *
 * @param \DateTimeInterface $startDate
 * @return Campaign
 */
public function setStartDate(\DateTimeInterface $startDate)
{
    $this->startDate = $startDate;

    return $this;
}

/**
 * Get startDate
 *
 * @return \DateTimeInterface
 */
public function getStartDate()
{
    return $this->startDate;
}

Then, you should have a better output. Note that 0000-00-00 00:00:00 is an invalid date...

For your error, you can make it like this

if(isset($formData["startDate"]) && !empty($formData["startDate"])) {
    $date = DateTime::createFromFormat('Y\.m\.d', $formData["startDate"]);
} else {
    $date = new DateTime('now');
}

$campaign->setStartDate($date);

Hope it's help

  • Related