Get the first month of the month for a given set of dates

What I need

I have a specific list of dates. I want to get the first Monday of every time.

for example: suppose datetimes are

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

I want to get the first Monday of all these datetimes, so the result leads to

  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")); 
0
source share
4 answers

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('Ym-d'); } 
+5
source
 <?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('Ym-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 
0
source

the first Monday will be during the first 7 days of the month, DAYOFWEEK(date) returns 1 = Sunday, 2 = Monday, etc.

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

0
source

You can scroll through an array of dates and then exit the loop and return $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; } } 

Exit

First Monday in list is - 2013-08-05

-one
source

Source: https://habr.com/ru/post/1495513/


All Articles