在给定日期的一周内获取所有工作日 [英] Get all Work Days in a Week for a given date

查看:119
本文介绍了在给定日期的一周内获取所有工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have one date as a string:

2011/06/01

我需要从那个星期五到星期五的五个工作日(星期一到星期五)获得5个DateTime对象。 >,例如对于上述日期,我需要2011-05-30到2011-06-03。

I need to get the 5 DateTime objects from it that correspond to the five weekdays (Monday to Friday) in that week, e.g. for the date above I need 2011-05-30 to 2011-06-03.

如何做?我知道我可以做:

How to do that? I know I can do:

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

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

But I am kinda stuck there :) I know, embarrassing.

推荐答案

可以使用 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 作为容器。

Note that DatePeriod is an Iterator, so unless you are really fixed on having the dates in an array, you can just as well go with the DatePeriod as container.

以上将会提供类似的内容( demo

The above will give something like (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之前的解决方案将是


One pre-5.3 solution to do that would be

$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))
    );
}

虽然我真的不明白为什么要使用DateTime对象你不会/不能在你的项目中使用他们的API。正如你所看到的,这是所有旧的日期函数,DateTime只是容器。

though I really dont see why you would want to use DateTime objects for this when you dont/cannot also use their API in your project. As you can see, this is all the old date functions with DateTime just being the container.

这篇关于在给定日期的一周内获取所有工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆