How to parse a faker dateTimeBetween with Carbon in laravel
Asked Answered
E

2

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
Elielia answered 29/8, 2017 at 4:52 Comment(5)
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?Knave
Sorry . I edited the question with the specific error.Elielia
Carbon::createFromTimestamp() takes a timestamp (unix timestamp) as first argument and not a DateTime-object, which $faker->dateTimeBetween() returns. Check out Carbons documentationKnave
Could you post the output of dd($events)Oppressive
This was helpful for me in understanding how to use Carbon and Faker together: https://mcmap.net/q/593344/-how-could-i-create-carbon-object-from-given-datetime-structure-duplicateThorton
K
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.

Knave answered 29/8, 2017 at 5:12 Comment(0)
E
3

that will return a carbon instance.

$date = \Carbon\Carbon::createFromTimeStamp($faker->dateTimeBetween('now', '+7 days')->getTimestamp());
Ecto answered 18/3, 2019 at 13:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.