作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
所以我有一个日期作为字符串:
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/
我是一名优秀的程序员,十分优秀!