Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

php - Get all Work Days in a Week for a given date

So I have one date as a string:

2011/06/01

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can use 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));

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.

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
    )
)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...