6

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
Jason
  • 213
  • 1
  • 4
  • 11
  • 1
    What does _"But its not working properly"_ mean? Where's the issue? Faker? Carbon? When you're trying to insert the data? Errors? Invalid data? – M. Eriksson Aug 29 '17 at 04:55
  • Sorry . I edited the question with the specific error. – Jason Aug 29 '17 at 04:58
  • `Carbon::createFromTimestamp()` takes a _timestamp (unix timestamp)_ as first argument and not a DateTime-object, which `$faker->dateTimeBetween()` returns. Check out [Carbons documentation](http://carbon.nesbot.com/docs/) – M. Eriksson Aug 29 '17 at 05:01
  • Could you post the output of `dd($events)` – linktoahref Aug 29 '17 at 05:02
  • This was helpful for me in understanding how to use Carbon and Faker together: https://stackoverflow.com/a/54798012/470749 – Ryan Feb 21 '19 at 01:52

2 Answers2

12

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.

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
2

that will return a carbon instance.

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