ma_dev_15
ma_dev_15

Reputation: 1196

Get next to next monday in PHP

How can i get 2nd monday after the input date? i have solution but that not feasible

$date = new DateTime();
$date->modify('next monday');
$next_monday = $date->format('Y-m-d');
$date = new DateTime($next_monday);
$date->modify('next monday');
$next_monday = $date->format('Y-m-d');

Please suggest me some method to do so.

Upvotes: 5

Views: 6883

Answers (3)

Pejman
Pejman

Reputation: 1358

You can do it with strtotime() but if you think it is too costly, you can use date and DateInterval as well.

$date = new DateTime('2017-02-15 13:03:00');
// move back to past Monday
$num = (date("w", $date->getTimestamp())) - 1;
$offset = new DateInterval("P{$num}D");
$offset->invert = 1;
// move forward two weeks
$interval = new DateInterval('P2W');
$next_second_monday = $date->add($offset)->add($interval);

And $next_second_monday will be:

DateTime Object
(
    [date] => 2017-02-27 13:03:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)

Upvotes: 2

Don't Panic
Don't Panic

Reputation: 41820

Your DateTime object's modify method takes the same type of arguments that strtotime does. You're already using 'next monday', you just need to use 'second monday' instead.

$date->modify('second monday');
echo $date->format('Y-m-d');

Also, in case you didn't know this, some of the DateTime methods can be chained:

echo $date->modify('second monday')->format('Y-m-d');

Upvotes: 4

Nicolas
Nicolas

Reputation: 8695

There is probably another way to do so but using MomentPHP You could get the start of today's week, adding 1 day ( to get to monday ) and then adding two week, you would get to the second next monday.
Something like that :

<?php
$m = \Moment\moment();
$sunday = $m->startOf('week');
$monday = $sunday->addDays(1);
$2nextMonday = $monday->addWeeks(2);

Upvotes: 0

Related Questions