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"));
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');
}
<?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'), "
";
echo find_the_first_monday('2013-08-05'), "
";
echo find_the_first_monday('2013-09-13'), "
";
// output:
// 2013-07-01
// 2013-08-05
// 2013-09-02
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
You could loop through the array of dates and then break out of the loop and return the $Date
when you first encounter Monday
$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