【问题标题】:Randomize timing by either adding or subtracting it from current time in php通过在php中添加或减去当前时间来随机化时间
【发布时间】:2020-02-10 18:19:38
【问题描述】:

我正在尝试在 Laravel 中播种数据库表。有一个 time 列,我需要对该表中的每条记录具有唯一性或至少不相同。

目前,我正在使用这个;这确实给出了我正在寻找的结果,但它并不完整。

mt_rand(0,23).":".str_pad(mt_rand(0,59), 2, "0", STR_PAD_LEFT)

我的问题是个位数时间前面没有 0,并且缺少 sec。通常,我计划的是下面的代码,但它一遍又一遍地让我得到相同的结果:

date('H:i:s', strtotime( ((srand(0,1) ? '-'.mt_rand(1,24) : '+'.mt_rand(1,24).' '.rand(0,1) ? 'minute' : 'hour')), strtotime(date('H:i:s')))),

结果总是"05:30:00",所以我不知道下一步该做什么。

【问题讨论】:

  • 对于寻找通用答案的人来说,这是我为 php 提出的解决方案。 // 得到 + / - 数 $xno = mt_rand(1,2) == 1 ? '-'.mt_rand(1,24) : '+'.mt_rand(1,24); // 获取分钟或 $xtime = mt_rand(1,2) == 1 ? $xno。分钟':$ xno。'小时'; $final = date('H:i:s', strtotime($xtime, strtotime(date('H:i:s'))));

标签: php laravel datetime time


【解决方案1】:

你说你使用的是 Laravel,那为什么不直接使用 DateTime generation 的内置 Faker 库呢?

$faker = Faker::create();
$faker->time('H:i')

从文档中,这里是可用的与 DateTime 相关的输出:

unixTime($max = 'now')                // 58781813
dateTime($max = 'now', $timezone = null) // DateTime('2008-04-25 08:37:17', 'UTC')
dateTimeAD($max = 'now', $timezone = null) // DateTime('1800-04-29 20:38:49', 'Europe/Paris')
iso8601($max = 'now')                 // '1978-12-09T10:10:29+0000'
date($format = 'Y-m-d', $max = 'now') // '1979-06-09'
time($format = 'H:i:s', $max = 'now') // '20:49:42'
dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Africa/Lagos')
dateTimeInInterval($startDate = '-30 years', $interval = '+ 5 days', $timezone = null) // DateTime('2003-03-15 02:00:49', 'Antartica/Vostok')
dateTimeThisCentury($max = 'now', $timezone = null)     // DateTime('1915-05-30 19:28:21', 'UTC')
dateTimeThisDecade($max = 'now', $timezone = null)      // DateTime('2007-05-29 22:30:48', 'Europe/Paris')
dateTimeThisYear($max = 'now', $timezone = null)        // DateTime('2011-02-27 20:52:14', 'Africa/Lagos')
dateTimeThisMonth($max = 'now', $timezone = null)       // DateTime('2011-10-23 13:46:23', 'Antarctica/Vostok')
amPm($max = 'now')                    // 'pm'
dayOfMonth($max = 'now')              // '04'
dayOfWeek($max = 'now')               // 'Friday'
month($max = 'now')                   // '06'
monthName($max = 'now')               // 'January'
year($max = 'now')                    // '1993'
century                               // 'VI'
timezone                              // 'Europe/Paris'

【讨论】:

  • 使用这个效果很好,$faker->time($format = 'H:i:s', $max = 'now')
【解决方案2】:

虽然考虑到您使用 Laravel,@leek 的回答可能会更好,但获取所需内容的更通用方法如下:

$dt = new DateTime();
var_dump($dt->format('H:i:s'));

但是,如果您每秒运行脚本超过一次,这将不够独特。当然,如果运行超过 1 天,它(可能)不会是唯一的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    相关资源
    最近更新 更多