简体   繁体   中英

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.

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

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
)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM