Laravel,Faker - 增加生成的日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26700446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:21:56  来源:igfitidea点击:

Laravel, Faker - Increment generated dateTime

phpdatetimelaravelincrementfaker

提问by Томица Кора?

I'm using Faker package in my Seeder to generate fake data for training events.

我在 Seeder 中使用 Faker 包为训练事件生成假数据。

Each event has starts_atand ends_atfields. I want to populate the ends_atfield with a DateTimethat is after the one generated for starts_at, preferably by 1 to 8 hours, or even a fixed 1 hour difference would be fine.

每个事件都有starts_atends_at字段。我想ends_atDateTime生成 之后的字段填充该字段starts_at,最好是 1 到 8 小时,甚至固定的 1 小时差异也可以。

回答by rmobis

Adapting the pattern described in Build APIs You Won't Hateand using the awesome Carbonpackage, here's how you can do it:

改编你不会讨厌的构建 API 中描述的模式并使用很棒的Carbon包,你可以这样做:

<?php

use Carbon\Carbon;
use Faker\Factory as Faker;

class UserEventsTableSeeder extends Seeder {

    public function run() {
        $faker = Faker::create();

        foreach (range(1, 15) as $index) {
            $startDate = Carbon::createFromTimeStamp($faker->dateTimeBetween('-1 years', '+1 month')->getTimestamp());

            UserEvent::create([
                // ...

                'starts_at' => $startDate->toDateTimeString(),
                'ends_at'   => $startDate->addHours( $faker->numberBetween( 1, 8 ) )
            ]);
        }
    }
}

回答by zak.http

here is an easy way to define the ends_at

这是定义ends_at的简单方法

$starts_at = Carbon::createFromTimestamp($faker->dateTimeBetween($startDate = '+2 days', $endDate = '+1 week')->getTimeStamp()) ;

$ends_at= Carbon::createFromFormat('Y-m-d H:i:s', $starts_at)->addHours( $faker->numberBetween( 1, 8 ) );