如何使用 Carbon 获得一年中的星期四
How To Get Thursdays Of Year Using Carbon
我想使用 Carbon 获取一年中的所有星期四并将其保存在 DB 上。
到目前为止我只能存储当月的星期四。请告诉我如何制作一整年一次。
当前代码:
public function getThursdays()
{
return new \DatePeriod(
Carbon::parse("first thursday of this month"),
CarbonInterval::week(),
Carbon::parse("first thursday of next month")
);
}
public function handle()
{
$thursdays = $this->getThursdays();
foreach ($thursdays as $thursday)
{
$Weeks = new Week();
$Weeks->week_starting_date = $thursday;
$Weeks->save();
}
}
你可以先用WEEKS_PER_YEAR
得到每年的周数,例如:
$weeks_per_year = Carbon::WEEKS_PER_YEAR;
之后使用 :
获取一年中的第一个星期四
$first_thursday = Carbon::parse("first thursday of this year");
然后循环遍历所有周,每周使用 Carbon 函数 addWeeks(1) 进行加法以获得下周的星期四,依此类推:
for($i=1;$i<$weeks_per_year;$i++)
{
array_push( $thursdays, $first_thursday->addWeeks(1)->toDateString() );
}
完整代码:
$weeks_per_year = Carbon::WEEKS_PER_YEAR;
$first_thursday = Carbon::parse("first thursday of this year");
$thursdays = [$first_thursday->toDateString()];
for($i=1;$i<$weeks_per_year;$i++)
{
array_push( $thursdays, $first_thursday->addWeeks(1)->toDateString() );
}
输出:
以下格式的全年星期四数组 yyyy-mm-dd
:
["2016-01-07","2016-01-14","2016-01-21", ... ,"2016-12-29"]
或者您可以直接将日期存储在您的数据库中,而不是像这样返回一个数组:
for($i=1; $i<$weeks_per_year;$i++){
$Weeks = new Week();
$Weeks->week_starting_date = $first_thursday->addWeeks(1)->toDateString();
$Weeks->save();
}
希望对您有所帮助。
我想使用 Carbon 获取一年中的所有星期四并将其保存在 DB 上。
到目前为止我只能存储当月的星期四。请告诉我如何制作一整年一次。
当前代码:
public function getThursdays()
{
return new \DatePeriod(
Carbon::parse("first thursday of this month"),
CarbonInterval::week(),
Carbon::parse("first thursday of next month")
);
}
public function handle()
{
$thursdays = $this->getThursdays();
foreach ($thursdays as $thursday)
{
$Weeks = new Week();
$Weeks->week_starting_date = $thursday;
$Weeks->save();
}
}
你可以先用WEEKS_PER_YEAR
得到每年的周数,例如:
$weeks_per_year = Carbon::WEEKS_PER_YEAR;
之后使用 :
获取一年中的第一个星期四$first_thursday = Carbon::parse("first thursday of this year");
然后循环遍历所有周,每周使用 Carbon 函数 addWeeks(1) 进行加法以获得下周的星期四,依此类推:
for($i=1;$i<$weeks_per_year;$i++)
{
array_push( $thursdays, $first_thursday->addWeeks(1)->toDateString() );
}
完整代码:
$weeks_per_year = Carbon::WEEKS_PER_YEAR;
$first_thursday = Carbon::parse("first thursday of this year");
$thursdays = [$first_thursday->toDateString()];
for($i=1;$i<$weeks_per_year;$i++)
{
array_push( $thursdays, $first_thursday->addWeeks(1)->toDateString() );
}
输出:
以下格式的全年星期四数组 yyyy-mm-dd
:
["2016-01-07","2016-01-14","2016-01-21", ... ,"2016-12-29"]
或者您可以直接将日期存储在您的数据库中,而不是像这样返回一个数组:
for($i=1; $i<$weeks_per_year;$i++){
$Weeks = new Week();
$Weeks->week_starting_date = $first_thursday->addWeeks(1)->toDateString();
$Weeks->save();
}
希望对您有所帮助。