0

I want to get the date for every Monday for this current Monday (or any other day).

I have tried this:

return date( 'm/d/Y', strtotime( "$passed_day next week" ) );
AstroCB
  • 12,337
  • 20
  • 57
  • 73
osos
  • 2,103
  • 5
  • 28
  • 42

3 Answers3

4

You can use relative date/time formats when creating or modifying DateTime objects.


Example:

$date = new DateTime('first Monday of this month');
$thisMonth = $date->format('m');

while ($date->format('m') === $thisMonth) {
    echo $date->format('Y-m-d'), "\n";
    $date->modify('next Monday');
}

Output:

2015-03-02
2015-03-09
2015-03-16
2015-03-23
2015-03-30
user3942918
  • 25,539
  • 11
  • 55
  • 67
1

A variant on Paul's answer, using DateInterval and DatePeriod

$begin = new DateTime('First monday of this month');
$end = new DateTime('First monday of next month');

// Every week
$interval = new DateInterval( 'P1W' );
$daterange = new DatePeriod( $begin, $interval ,$end );

foreach($daterange as $date){
    echo $date->format('Y-m-d');
}
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
0

Or use default date() function :

function mondays ( $date ) {
    $mondays = [ ];

    $start = date( 'N', strtotime( $date ) );
    $month = date( 'm', strtotime( $date ) );

    $closest_monday             = strtotime( $date ) - ( $start - 1 ) * 60 * 60 * 24;
    if ( $month == date( 'm', $closest_monday ) ) {
        $mondays[ $closest_monday ] = date( 'N d-m-Y', $closest_monday );
    } else {
        $closest_monday = strtotime( $date ) + ( 8 - $start ) * 60 * 60 * 24;
        $mondays[ $closest_monday ] = date( 'N d-m-Y', $closest_monday );
    }

    for ( $i = 1; $i < 6; $i++ ) {
        $prev = $closest_monday - $i * 7 * 60 * 60 * 24;
        $next = $closest_monday + $i * 7 * 60 * 60 * 24;
        if ( $month == date( 'm', $next ) ) {
            $mondays[ $next ] = date( 'N d-m-Y', $next );
        }
        if ( $month == date( 'm', $prev ) ) {
            $mondays[ $prev ] = date( 'N d-m-Y', $prev );
        }
    }
    ksort( $mondays );

    return $mondays;
}

Outputs for $date = '02-02-2014';

array (size=4)
  1391382000 => string '1 03-02-2014' (length=12)
  1391986800 => string '1 10-02-2014' (length=12)
  1392591600 => string '1 17-02-2014' (length=12)
  1393196400 => string '1 24-02-2014' (length=12)
xAqweRx
  • 1,236
  • 1
  • 10
  • 23