PHP - DateTime::__construct(): Failed to parse time string

Viewed 1780

I am pulling DateTime timestamp result from another table which is set as:

When dumping specific value of $post->getUploadTime() I get:

"2602585961"

It's in string format.

In my entity I have modified the setter to:

public function setStartTime($startTime)
{
    $date = new \DateTime($startTime);
    $this->startTime = $date->getTimestamp();
    return $this;
}

And my code:

$newEntityObject->setStartTime(intval($post->getUploadTime()));

I am using intval() to transform string to integer (timestamp) so I can insert it in db but I get an error:

DateTime::__construct(): Failed to parse time string (2602585961) at position 8 (6): Unexpected character"

It's an error with or without the intval(). I can not figure out what is wrong?

I know there are a lot of posts about the issue. I tried them, but the problem still remains.

3 Answers

Try :

$date = new \DateTime();
$date->setTimestamp($startTime);
$this->startTime = $date->getTimestamp();

But since you are trying to assign a timestamp to your startTime property and you are already passing a timestamp to your function you can just assign whatever timestamp you are passing:

$this->startTime = $startTime;

You have a timestamp, and you are trying to make it a DateTime and get timestamp from the new datetime object.

The DateTime constructor only accept specific date and time format.

Also, the given value refer to the year 2052. So it's possible that you have another issue before.

You don't need to convert to a number. Because you need a string argument that starts with @ You need use @. Read Documentation.

 <?php
    
    $a = "@2602585961";
    
    function setStartTime($startTime)
    {
        $date = new \DateTime($startTime);
        $b = $date->getTimestamp();
        return $b;
    }
    
    echo setStartTime($a);

https://www.php.net/manual/ru/datetime.formats.compound.php

In your code:

$newEntityObject->setStartTime("@" .  $post->getUploadTime());
Related