Kannan Ramamoorthy
Kannan Ramamoorthy

Reputation: 4180

Faker having end date greater than start date

We are using Faker for our Laravel app. For a table we have 2 columns, start date and end date. How to call faker in a way that the end date will always be greater than start date

Upvotes: 4

Views: 13072

Answers (4)

AverageJoe
AverageJoe

Reputation: 131

I know thsis was asked a long long time ago in a galaxy far far away, but none of the sugested solutons worked for me so hopefully this will help someone else in the future. However Pillip Reiber's suggestion did put me on the right track.

I have an event that only runs 2-3 days max and has a start_date and end_date, with an early_cut_off_date roughly 2 weeks prior. This was my solution:

// set the start_date to be between 6 months ago and 6 months from now 
// so we can deal with expired events
$start_date = $this->faker->dateTimeBetween('-6 months', '+6 months');

/* set the end_date to be the start_date plus 3 days 
(or however long your event lasts - approximately). 
While it is weird that you have to use dateTimeBetween(), and supply a 
start and end that are the same, setting them to the same value, makes them land at the
specified length (+3 days in my example)
*/
$end_date = $this->faker->dateTimeBetween(
                $start_date->format('Y-m-d H:i:s').' +3 days',
                $start_date->format('Y-m-d H:i:s').' +3 days'
            );

// set the early_date to be 2 weeks before the start_date
$early_date = $this->faker->dateTimeBetween(
                  $start_date->format('Y-m-d H:i:s').' -2 weeks',
                  $start_date->format('Y-m-d H:i:s').' -2 weeks'
              );

Upvotes: 0

Rishni Meemeduma
Rishni Meemeduma

Reputation: 384

You can do something like this,

Start date ,Create a random start date within, one month ago and one month from now.

$star_date = Carbon::instance($faker->dateTimeBetween('-1 months','+1 months'));

To modify date by couple of days in to future

$end_date = (clone $start_date)->addDays(random_int(0,14));

Upvotes: 1

Philipp Rieber
Philipp Rieber

Reputation: 1581

Create a random start date in the space of time you wish:

$start = $faker->dateTimeBetween('next Monday', 'next Monday +7 days');

Then use the returned start date as the minimum input for the end date and make sure that the upper boundary for your end date is also after your start date.

$end = $faker->dateTimeBetween($start, $start->format('Y-m-d H:i:s').' +2 days');

You may also consider using Alice for creating fixtures using nice and readable YAML. You can use variables in Alice code to achieve your goal.

For the relative date/time syntax checkout the PHP docs.

Upvotes: 15

Jilson Thomas
Jilson Thomas

Reputation: 7303

You can do as follows:

'start_date' => $faker->date,
'end_date'   => $faker->dateTimeBetween($startDate = '-30 years', $endDate = 'now'),

Upvotes: 2

Related Questions