【问题标题】:Laravel/PHP/Carbon parse a date to one and three days from now() to the hour, disregarding minutes and secondsLaravel/PHP/Carbon 将日期解析为从 now() 到小时的一到三天,不考虑分钟和秒
【发布时间】:2019-03-08 07:28:44
【问题描述】:

我正在使用 Laravel 5.4 和 Carbon 来查找恰好在 laravel 作业前一天和三天(到小时)发送通知的日期。例如,如果日期是2019-03-10 18:00:032019-03-10 18:15:34,我想明天在2019-03-07 18:00:002019-03-09 18:00:00 发送通知。我想在一个雄辩的查询中做到这一点,但不确定如何按天和小时“惰性匹配”。如果我有一个带有start_date 时间戳的Appointment 模型,我知道我可以按天或日期进行精确匹配,但我想找到不考虑小时/秒的匹配。我正在考虑这些方面的事情:

$oneDayAppointments = Appointment::whereDay(
    'start_date',
    Carbon::now()->addDay()->day
)->get();

...如果 start_date 是从现在开始的一天,我会得到任何约会。现在我将如何将它磨练到一天和一小时。如果我只使用 where 子句:

$oneDayAppointments = Appointment::where(
    'start_date',
    Carbon::now()->addHours(24)
)->get();

...我可以得到完全匹配,但前提是分钟/秒也是匹配的。谢谢!

【问题讨论】:

  • 您需要在查询之前使用日期对象以获取当前日期时间,但删除分钟和秒并添加一天。一旦有了这个日期,您就需要创建一个“到”日期时间,即该日期到小时 + 1 小时 - 1 秒。一旦有了这两个日期时间,就可以在 eloquent 查询中使用 whereBetween

标签: laravel laravel-5 eloquent laravel-5.4 php-carbon


【解决方案1】:

根据我上面的评论,应该这样做

$tomorrowStart = Carbon::createFromFormat('Y-m-d H:i:s', Carbon::now()->addDay()->format('Y-m-d H:00:00'));
$tomorrowEnd = $tomorrowStart->copy()->addHour()->subSecond();


//whereBetween('start_date', [$tomorrowStart, $tomorrowEnd])

https://laravel.com/docs/5.8/queries

【讨论】:

  • 你明白它在做什么吗?另外,如果您在时间戳上使用时区,请小心。
  • 是的,我也考虑过。谢谢!
  • 另外,为您的 start_date 字段添加一个索引 - 否则这将导致顺序扫描并且随着更多记录的填充而变慢。创建一个新的迁移,或者如果您可以回滚并重新开始,请添加到模型的原始迁移文件中:$table->timestamp('start_date')->index();
猜你喜欢
  • 1970-01-01
  • 2017-01-04
  • 2016-05-06
  • 2015-08-21
  • 1970-01-01
  • 2016-01-07
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多