简体   繁体   English

循环浏览给定的日期

[英]Loop through the given dates

I have a weird scenario like I have given four dates and I need to call a method based on these dates. 我有一个奇怪的场景,例如我给了四个日期,我需要根据这些日期调用一个方法。 That is first I need to call the function for start time as 1st of the month and end time as 15th of the month. 首先,我需要调用该函数的开始时间为该月的1号,结束时间为该月的15号。 This function again needs to be called for start time 16th of the month and end date 30th/31st of the month. 再次需要在每月的16号开始时间和每月30/31号的结束日期调用此函数。 I can call the functions two times with hard-coded values, but is there any better method to do this? 我可以使用硬编码的值两次调用函数,但是有没有更好的方法呢?

I am using Carbon library for PHP and creating the dates like this 我正在将Carbon库用于PHP并创建这样的日期

$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();

and the method I need to call have the following code 和我需要调用的方法具有以下代码

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

These will give the corresponding dates and now I need to run the method as start time as firstDay and end time as firstHalf and then again to call with start time as secondStart and end as lastDay . 这些将给出相应的日期,现在我需要将方法作为开始时间作为firstDay并将结束时间作为firstHalf ,然后再次以开始时间作为secondStart并作为lastDay结束进行lastDay Basically what I am trying to do is to avoid the duplication of the code by writing the query two times. 基本上我想做的是通过两次编写查询来避免代码重复。

How can this be done? 如何才能做到这一点?

You might be better off setting the variables to the actual Carbon instances. 您最好将变量设置为实际的Carbon实例。

Taking into consideration months that have 28 or 29 days, you can grab the last day of the previous month and divide that by 2 to find the mid-point. 考虑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();

Edit: updated example to reflect the variables used in your updated question 编辑:更新示例以反映更新问题中使用的变量

Edit 2: If you're using Laravel/Eloquent, you may even be able to pass the actual Carbon instances directly to the Query Builder, without calling toDateString() . 编辑2:如果您使用的是Laravel / Eloquent,您甚至可以将实际的Carbon实例直接传递给查询生成器,而无需调用toDateString()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM