所以我有一个日期作为字符串:
2011/06/01
我需要从中获取5个DateTime对象,这些对象对应于该周的五个工作日(周一至周五) ,例如对于上述日期,我需要2011-05-30至2011-06-03。
怎么做?我知道我能做到:
$dateTime = new DateTime('2011/06/01');
但我有点卡在那里:)我知道,令人尴尬。
答案 0 :(得分:7)
可以使用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
)
)
一个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只是容器。
答案 1 :(得分:1)
答案 2 :(得分:1)
您可以获得一周中的日期数(日期('w')0(星期日)到6(星期六)。从这里你可以用strtotime(“+ 1 DAY”,[你的时间戳])来完成其余的工作日,依此类推。如果你有日期,你可以制作对象。
答案 3 :(得分:0)
这似乎有效:
$d = date('N', strtotime('2011/06/01'));
// here N means ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
$week = array();
for($i = 1; $i < $d; ++$i){
$dateTime = new DateTime('2011/06/01');
for($j = 0; $j < $i; ++$j){
$dateTime->modify('-1 day');
}
$week[] = $dateTime;
}
$week[] = new DateTime('2011/06/01');
for($i = $d+1; $i <= 7; ++$i){
$dateTime = new DateTime('2011/06/01');
for($j = 0; $j < $i - $d; ++$j){
$dateTime->modify('+1 day');
}
$week[] = $dateTime;
}
sort($week);
foreach($week as $day){
echo $day->format('Y-m-d H:i:s'), '<br />';
}
答案 4 :(得分:0)
我已经完成了整整一周的时间。 我创建了一个函数,该函数返回一周中所有天的列表。 我让您下面的代码
public function daysOfWeekXML($day)
{
// Give number of day in the week
$day_number = date('N', strtotime($day));
$day_week_futur = [];
$day_week_past = [];
// Retrieve future days in the week
for ($i = $day_number; $i <= 7; $i++) {
$next_day = strtotime('+' . $i - $day_number . ' day', strtotime($day));
array_push($day_week_futur, date('Y-m-d', $next_day));
}
// Retrieve days past in the week
for ($day_number; $day_number > 1; $day_number--) {
$previous_day = strtotime('-' . ($day_number - 1) . ' day', strtotime($day));
array_push($day_week_past, date('Y-m-d', $previous_day));
}
// Concatenate all days in the week in array
return array_merge($day_week_past, $day_week_futur);
}