gpt4 book ai didi

php - 检索一个月中的所有特定日期

转载 作者:可可西里 更新时间:2023-11-01 01:13:43 25 4
gpt4 key购买 nike

我正在尝试使用 Carbon 检索自过去特定日期以来的所有星期一和星期二以及每个月的最后一个星期日。然后我想遍历天数并为那天创建一个偶数。我想弄清楚该怎么做?

// Get all dates of Mondays, Tuesdays, last Sundays of every Month since the first Monday of January of 2000.
$eventDates = Carbon::parse('first Monday of January 2000');

$i = 0;
while($eventDates->lt(Carbon::now()->subDay(14))) {

$event = factory(Event::class)->create([
'date' => $eventDate,
]);
}

最佳答案

我确信有一种更高效的方法可以做到这一点,但我对 Carbon 不是很熟悉。在这里,您将获得 3 个数组,每个数组对应自 2000 年以来每个月的每个星期一、星期二和最后一个星期日。然后您可以遍历每个 DatePeriod,或合并间隔以获得一个大的 DatePeriod,创建您的事件。

<?php
use Carbon\Carbon;
use Carbon\CarbonInterval;
$monday = Carbon::parse('First Monday of January 2000');
$tuesday = Carbon::parse('First Tuesday of January 2000');
$sunday = Carbon::parse('Last Sunday of January 2000');
$now = Carbon::now();
$mondays = new DatePeriod(
$monday,
CarbonInterval::week(),
$now
);
$tuesdays = new DatePeriod(
$tuesday,
CarbonInterval::week(),
$now
);
$sundays = new DatePeriod(
$sunday,
CarbonInterval::week(4),
$now
);

$allDays = [];
foreach ($mondays as $day) {
$allDays[] = $day;
}
foreach ($tuesdays as $day) {
$allDays[] = $day;
}
foreach ($sundays as $day) {
$allDays[] = $day;
}
usort($allDays, function ($a, $b) {
return strtotime($a) - strtotime($b);
});
foreach ($allDays as $day) {
echo $day->format("M D Y-m-d")."<br>";
}

关于php - 检索一个月中的所有特定日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45802629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com