How to handle Daylight saving time in laravel/php?

54 Views Asked by At

In the following code, i update or create a post based on the values that i receive from an api,

                  $this->channel->posts()->updateOrCreate([
                        'identifier' => $post->getId(),
                    ],
                        [
                            'title' => $post->getTitle(),
                            'description' => $post->getDescription(),
                            'posted_at' => $post->getPublishedAt(),
                        ]);

In the instance where posted_at = '2023-03-26 02:36:24', i get this error :

Illuminate\Database\QueryException SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2023-03-26 02:36:24' for column 'posted_at' at row 1 (SQL: update table_name set posted_at = 2023-03-26 02:36:24, table_name.updated_at = 2023-11-16 10:14:52 where id = 934579)

Which happens because the datetime value falls in the DST, this is the original format the datetime value was returned from the api "2023-03-26T02:36:24+0000" and the server timezone is "UTC"

the setPublishedAt function parses the value as below :

    public function setPublishedAt($publishedAt)
    {
        if (is_numeric($publishedAt)) {
            $this->publishedAt = Carbon::createFromTimestamp($publishedAt);
        } else {
            $this->publishedAt = Carbon::parse($publishedAt);
        }

        return $this;
    }

but it doesn't handle the issue.

0

There are 0 best solutions below