-5

I need next 5 saturday from the last month. eg. current date is 07-04-2018 so I need 5 saturday of the last month. output- 03-03-18, 10-03-18, 17-03-18, 24-03-18, 31-03-18. I can get it by using below but this is completely hardcoded. How can i apply here loop to get next five saturday of the last month?

$firstSat= date("dmy", strtotime("first saturday of last month"));
$secondSat= date("dmy", strtotime("second saturday of last month"));
$thirdSat= date("dmy", strtotime("third saturday of last month"));
$forthSat= date("dmy", strtotime("fourth saturday of last month"));
$fifthSat= date("dmy", strtotime("fifth saturday of last month"));
Abhishek Gurjar
  • 7,152
  • 9
  • 35
  • 40

1 Answers1

1

You can use new DateTime()

$y = 2018;
$m = 3;

$sat1 = new DateTime("first saturday of $y-$m");
$sat2 = new DateTime("second saturday of $y-$m");
$sat3 = new DateTime("third saturday of $y-$m");
$sat4 = new DateTime("fourth saturday of $y-$m");
$sat5 = new DateTime("fifth saturday of $y-$m");

echo $sat1->format('dmy') . "<br />";
echo $sat2->format('dmy') . "<br />";
echo $sat3->format('dmy') . "<br />";
echo $sat4->format('dmy') . "<br />";
echo $sat5->format('dmy') . "<br />";

This will result to:

030318
100318
170318
240318
310318

Getting all Saturdays of a month

$date = "03/17/18"; //Date on mm/dd/yy format

$start = new DateTime($date);
$end = new DateTime($date);
$end = $end->add(new DateInterval('P40D'));

$satPeriod = new DatePeriod (
    $start,
    DateInterval::createFromDateString('next saturday'),
    $end
);

foreach ($satPeriod as $saturday) {
    echo $saturday->format("dmy");
    echo "<br />";
}

This will result to:

170318
240318
310318
070418
140418
Eddie
  • 25,279
  • 6
  • 26
  • 53
  • Thanks Eddie. I don't want to write 5 lines for 5 saturday. I just want If I get the 1st saturday of the last month then next 4 saturday from the 1st saturday of the last month. – Devendra Vastrakar Apr 07 '18 at 05:41
  • @DevendraVastrakar I added new update. This will echo all Saturdays on the month – Eddie Apr 07 '18 at 05:50
  • I thing one last saturday is not coming(310318). Is there any way to get next saturday of the given date. Eg. **next saturday of 03-03-2018** – Devendra Vastrakar Apr 07 '18 at 06:08
  • Thanks. What about if I have date like 17-03-18 and want next 5 saturday date. eg. 24-03-18, 31-03-18, 07-04-18, 14-04-18,21-04-18 – Devendra Vastrakar Apr 07 '18 at 09:39
  • @DevendraVastrakar Updated answer, this answer will give 5-6 Saturdays. Just remove the exceeding saturdays – Eddie Apr 07 '18 at 10:01