【问题标题】:Loop through the given dates循环遍历给定的日期
【发布时间】:2018-01-24 10:27:45
【问题描述】:

我有一个奇怪的场景,比如我给出了四个日期,我需要根据这些日期调用一个方法。那是首先我需要调用函数,将开始时间作为本月的 ​​1 日,将结束时间作为本月的 ​​15 日。该函数需要在每月 16 日的开始时间和每月 30/31 日的结束日期再次调用。我可以用硬编码的值调用函数两次,但是有没有更好的方法来做到这一点?

我正在使用用于 PHP 的 Carbon 库并创建这样的日期

$this->firstDay = Carbon::now()->startOfMonth()->subMonth()>toDateString();

$this->lastDay = Carbon::now()->subMonth()->endOfMonth()>toDateString();

$this->firstHalf   = Carbon::parse($this->firstDay)->addDays(15)->toDateString();

$this->secondStart = Carbon::parse($this->firstDay)->addDays(16)->toDateString();

我需要调用的方法有以下代码

return $this
            ->database
            ->table('table')
            ->selectRaw('SUM(points) AS points, id')
            ->whereBetween('date', [$firstDay, $firstHalf])
            ->groupBy('id')
            ->get();

这些将给出相应的日期,现在我需要以firstDay 的开始时间和firstHalf 的结束时间运行该方法,然后以secondStart 的开始时间和lastDay 的结束时间再次调用。基本上我要做的是通过两次编写查询来避免代码重复。

如何做到这一点?

【问题讨论】:

  • 运行什么方法?不清楚“如何做到这一点?”中的“this”是什么,或者具体的问题是什么
  • 执行查询的方法,其中这些日期将作为介于之间的值。
  • 那里有什么问题?建议您使用一组更具体的详细信息更新问题。没有任何迹象表明当前问题中有任何查询,只是模糊提及 "method"
  • 已更新。我想要做的是在某个循环或某事中调用该方法,因此我不需要使用这两个日期范围编写两次查询
  • 只需将其包装在一个传入 2 个日期并返回这些结果的函数中,然后调用函数两次

标签: php loops date


【解决方案1】:

最好将变量设置为实际的 Carbon 实例。

考虑到有 28 天或 29 天的月份,您可以获取上个月的最后一天并将其除以 2 以找到中间点。

$lastMonth = Carbon::now()->subMonth();

$start = $lastMonth->startOfMonth();
$end = $lastMonth->endOfMonth();
$middle = floor($end->days / 2);

$firstDay = $start->toDateString();
$firstHalf = $start->addDays($middle)->toDateString();

$lastDay = $end->toDateString();
$secondHalf = $start->addDays($middle + 1)->toDateString();

编辑:更新示例以反映更新问题中使用的变量

编辑 2: 如果您使用 Laravel/Eloquent,您甚至可以将实际的 Carbon 实例直接传递给查询生成器,而无需调用 toDateString()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多