eskimo
eskimo

Reputation: 2624

Laravel Factory incorrect datetime value

In a Laravel Factory I have:

'created_at' => now()->subDays(mt_rand(1,90))->subHours(mt_rand(1,23))->toDateTimeString()

This previously worked fine, I think it was on Laravel 7.2. By 'worked fine' I mean I ran this to insert 10.000s or more rows and it never failed. After updating to 7.10.3 I now get the following error:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2020-03-29 02:10:11' for column 'created_at'

It does actually insert a few hundred rows before failing, so it seems to be a specific date or time that fails. Of the rows that are actually inserted some also have 2020-03-29 as the date and some have 02:10:11 as the time so I don't know why this is an 'invalid format'.

Upvotes: 1

Views: 634

Answers (1)

patricus
patricus

Reputation: 62228

March 29, 2020 was when daylight savings time (DST) started in Europe. I'm assuming you are in the Central European Time (CET) timezone, where time moves forward 1 hour from 2AM to 3AM, so there was no 2:10 AM, making your datetime invalid.

You have a couple options:

  1. You can update your database/database server to use UTC.
  2. You can update your Laravel application timezone to match your database server timezone (app.timezone config key).
  3. You can update your factory to call setTimezone(/* db timezone */) on your Carbon instance before converting it to a string (this will ensure Carbon does not create an invalid datetime for the database timezone).

Upvotes: 5

Related Questions