MSD
MSD

Reputation: 349

Get mondays tuesdays etc

How can I echo all dates for mondays/ wednesday / friday between these two dates?

This is what I have been working with:

    function get_days ( $s, $e )
{
    $r = array ();
    $s = strtotime ( $s . ' GMT' );
    $e = strtotime ( $e . ' GMT' );

    $day = gmdate ( 'l', $s );

    do
    {
        $r[] = $day . ', ' . gmdate ( 'Y-m-d', $s );

        $s += 86400 * 7;

    } while ( $s <= $e );

    return $r;
}

print_r ( get_days ( $start, $end ) );

Upvotes: 0

Views: 573

Answers (3)

AJ.
AJ.

Reputation: 28204

Try this:

function getDates($start_date, $end_date, $days){

    // parse the $start_date and $end_date string values
    $stime=new DateTime($start_date);
    $etime=new DateTime($end_date);

    // make a copy so we can increment by day    
    $ctime = clone $stime;
    $results = array();
    while( $ctime <= $etime ){

        $dow=$ctime->format("w");
        // assumes $days is array containing integers for Sun (0) - Sat (6)
        if( in_array($dow, $days) ){ 
            // make a copy to return in results
            $results[]=clone $ctime;
        }
        // incrememnt by 1 day
        //$ctime=date_add($ctime, date_interval_create_from_date_string('1 days'));
        $ctime->modify("+1 days");
    }

    return $results;
}

// get every Tues, Wed, Fri from now to End of June
getDates('2011-06-15','2011-06-30',array(2,3,5));

Upvotes: 1

James C
James C

Reputation: 14169

<?php

$start = "1 Jan 2011";
$end = "20 Jan 2011";

$dates = getDays($start, $end);

print_r($dates);

function getDays($start,$end)
{
    $t = new DateTime("$start 12:00");
    $e = new DateTime($end ." 12:00");

    $out = array();
    for (; $t<=$e; $t->modify("+1 day")) {
        $day = $t->format("D");
        if (in_array($day, array('Mon','Wed','Fri'))) {
            $out[] = $t->format('d M Y');
        }
    }

    return $out;
}

Upvotes: 0

Arjan
Arjan

Reputation: 9884

You should be able to get the days using strtotime(). It accepts arguments like next Tuesday and also parses 2011-06-15 into a correct timestamp. And yes, you need one (or more) loop(s).

This should be sufficient to point you in the right direction.

Ok, you updated your question while I was writing my answer. You can't assume that a day always has 86400 seconds. When DST starts or ends your assumption will be incorrect.

Upvotes: 0

Related Questions