How to parse a faker dateTimeBetween with Carbon in laravel

11.7k Views Asked by At

I am generating fake dates between a specific interval with faker. Generated dates result TIMESTAMP formate. I need to format it like 'Y-m-d' for insert into MySQL database table.

$events = $faker->dateTimeBetween('-30 days', '+30 days');
$dateFormate = Carbon::createFromTimestamp('Y-m-d H:i:s', $events )->format('Y-m-d');

But in the time of database seeding it gives an error

 [ErrorException]
  A non well formed numeric value encountered
2

There are 2 best solutions below

0
On BEST ANSWER

You're using both Carbon and the result from faker wrong (you don't need to use Carbon at all).

This row:

$events = $faker->dateTimeBetween('-30 days', '+30 days');

returns a DateTime instance. If you want to get the date in the format "Y-m-d" from a DateTime instance, all you need to do is to call DateTime:format():

$dateFormat = $events->format('Y-m-d');

That should give you the date in the format you want.

0
On

that will return a carbon instance.

$date = \Carbon\Carbon::createFromTimeStamp($faker->dateTimeBetween('now', '+7 days')->getTimestamp());