gpt4 book ai didi

php - 获取给定日期一周内的所有工作日

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

所以我有一个日期作为字符串:

2011/06/01

我需要从中获取 5 个 DateTime 对象,它们对应于该周的五个工作日(周一至周五),例如对于上面的日期,我需要 2011-05-30 到 2011-06-03。

该怎么做?我知道我能做到:

$dateTime = new DateTime('2011/06/01');

但我有点卡在那里 :) 我知道,很尴尬。

最佳答案

可以使用DatePeriod :

$firstMondayThisWeek= new DateTime('2011/06/01');
$firstMondayThisWeek->modify('tomorrow');
$firstMondayThisWeek->modify('last Monday');

$nextFiveWeekDays = new DatePeriod(
$firstMondayThisWeek,
DateInterval::createFromDateString('+1 weekdays'),
4
);

print_r(iterator_to_array($nextFiveWeekDays));

请注意 DatePeriod 是一个 Iterator,因此除非您真的固定将日期放在数组中,否则您也可以使用 DatePeriod 作为容器。

上面会给出类似 ( demo )

 Array
(
[0] => DateTime Object
(
[date] => 2011-05-30 00:00:00
[timezone_type] => 3
[timezone] => Europe/Berlin
)

[1] => DateTime Object
(
[date] => 2011-05-31 00:00:00
[timezone_type] => 3
[timezone] => Europe/Berlin
)

[2] => DateTime Object
(
[date] => 2011-06-01 00:00:00
[timezone_type] => 3
[timezone] => Europe/Berlin
)

[3] => DateTime Object
(
[date] => 2011-06-02 00:00:00
[timezone_type] => 3
[timezone] => Europe/Berlin
)

[4] => DateTime Object
(
[date] => 2011-06-03 00:00:00
[timezone_type] => 3
[timezone] => Europe/Berlin
)
)

一个 pre-5.3 的解决方案是

$firstMondayInWeek = strtotime('last Monday', strtotime('2011/06/01 +1 day'));
$nextFiveWeekDays = array();
for ($days = 1; $days <= 5; $days++) {
$nextFiveWeekDays[] = new DateTime(
date('Y-m-d', strtotime("+$days weekdays", $firstMondayInWeek))
);
}

虽然我真的不明白为什么当你不/不能在你的项目中使用它们的 API 时你会想要为此使用 DateTime 对象。如您所见,这是所有旧的日期函数,DateTime 只是容器。

关于php - 获取给定日期一周内的所有工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6202576/

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