Avinash
Avinash

Reputation: 2005

Get first monday of month for a given set of datetimes

What I Require

I have a certain list of datetimes. I want to get the first monday of each datetimes.

eg: Suppose the given datetimes are

 2013-07-05 2013-08-05, 2013-09-13 etc.

I want to get the first monday of all these datetimes such that the output results in

 2013-07-01, 2013-08-05, 2013-09-02 respectively

I am actually stuck with this using stftime.

strftime("%d/%m/%Y", strtotime("first Monday of July 2012"));

Upvotes: 6

Views: 12944

Answers (5)

temo
temo

Reputation: 698

I know this is an old question and my answer is not 100% solution for this question, but this might be usefull for someone, this will give "first Saturday of the given year/month":

date("Y-m-d", strtotime("First Saturday of 2021-08")); // gives: 2021-08-07

You can manipulate this in many ways.

obviously you can put "Second Saturday of year-month" and it will find that as well.

Works with PHP 5.3.0 and above (tested at https://sandbox.onlinephpfunctions.com/).

Upvotes: 3

Developer
Developer

Reputation: 1040

Using php Datetime class:

$Dates = array('2013-07-02', '2013-08-05', '2013-09-13');
foreach ($Dates as $Date)
{
    $test = new DateTime($Date);
    echo $test->modify('first monday')->format('Y-m-d');
}

Upvotes: 11

Kevin Lynch
Kevin Lynch

Reputation: 24703

You could loop through the array of dates and then break out of the loop and return the $Date when you first encounter Monday

PHPFIDDLE

$Dates = array('2013-07-02', '2013-08-05', '2013-09-13');

foreach ($Dates as $Date)
{
    $weekday = date('l', strtotime($Date));
    if($weekday == 'Monday') { 
        echo "First Monday in list is - " . $Date;
        break; 
    }
}

Output

First Monday in list is - 2013-08-05

Upvotes: -1

Joy
Joy

Reputation: 21

the first monday would be within the first 7 days of a month, DAYOFWEEK(date) returns 1=sunday, 2=monday, and so on

also see the hack#23 http://oreilly.com/catalog/sqlhks/chapter/ch04.pdf

Upvotes: 0

srain
srain

Reputation: 9082

<?php
function find_the_first_monday($date)
{
    $time = strtotime($date);
    $year = date('Y', $time);
    $month = date('m', $time);

    for($day = 1; $day <= 31; $day++)
    {
        $time = mktime(0, 0, 0, $month, $day, $year);
        if (date('N', $time) == 1)
        {
            return date('Y-m-d', $time);
        }
    }
}

echo find_the_first_monday('2013-07-05'), "\n";
echo find_the_first_monday('2013-08-05'), "\n";
echo find_the_first_monday('2013-09-13'), "\n";

// output:
// 2013-07-01
// 2013-08-05
// 2013-09-02

Upvotes: 0

Related Questions