Home > Net >  Is it possible to resrtict the hours in laravel faker->dateTimeBetween? If so, how?
Is it possible to resrtict the hours in laravel faker->dateTimeBetween? If so, how?

Time:01-26

So I'm using faker to seed the database with data for testing. Right now, when I use 'created_at' => $this->faker->dateTimeBetween('-5 years', '-3 days') it breaks and says

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2018-03-25 02:45:11' for column

I've looked it up and as mentioned here,

This is most likely a timezone conversion error on the day of standard-time to daylight-time switchover. The hour from 0200 to just before 0300 does not exist.

Is there a way to prevent that from happening? For example, specifying that the dateTimeBetween can only select hours between 6 and 18?

Edit #1: This mostly happens when I try to seed with 10k data (for testing speed, cache, and other stuff).

CodePudding user response:

You'll probably have to add in an extra step to convert it to a DateTime or Carbon object:

'created_at' => Carbon::parse($this->faker->dateTimeBetween('-5 years', '-3 days'))->toDateTimeString()

This will force the faker date into a Carbon instance, which should convert the date properly. For instance, if I do

DateTime::createFromFormat('Y-m-d H:i:s', '2018-03-11 02:45:11');

while in a US Eastern timezone, the date becomes 2018-03-11 03:45:11.0 America/New_York (-04:00)

Also make sure that Laravel and MySQL are on the same timezone (or use Carbon to convert the timezone), or use UTC.

  • Related