2

I have a PHP DateTime object that looks like this...

$startdate = '01/05/2019';
$mydate = DateTime::createFromFormat("d/m/Y", $startdate);

Is there a way to advance this date to the nearest 17th of the month? The start date will be dynamic so I cant hardcode it.

Does anybody have an example?

4
  • 6
    What if the nearest is in the past?
    – John Conde
    May 8, 2019 at 13:24
  • Very good point, this will only ever be for dates in the future May 8, 2019 at 13:24
  • 3
    $mydate->setDate($mydate->format('Y'), $mydate->format('m'), 17), with a bit of if..else to figure out whether you want to increase the month by 1 or not…?
    – deceze
    May 8, 2019 at 13:27
  • 1
    @fightstarr20 then "Is there a way to advance this date to the nearest 17th of the month?" this is an incorrect statement if you're only looking forward in time. According to that if it was the 18th, you'd want it to the next month. Could you make your question more clear?
    – user5283119
    May 8, 2019 at 13:49

2 Answers 2

3

Add one day to your date until you find the next 17th.

<?php
$startdate = '2019-01-05';
$interval = new DateInterval('P1D'); // define interval as 1 day
$date = new DateTime($startdate);

while($date->format('j') != 17){
    $date->add($interval);
}
echo $date->format('Y-m-d') . "\n";

Output: 2019-01-17

2

The trick here is to find the first date of the appropriate month, then add sixteen days.

These modify() expressions are helpful.

   $mydate->modify ("first day of this month")->modify("+ 16 days");
   $mydate->modify ("first day of next month")->modify("+ 16 days");

Next, you can figure out which one you want:

  if ($mydate->format("d") > 17) ...

Put it all together like this:

$mydate = DateTime::createFromFormat("d/m/Y", $startdate);
if ($mydate->format("d") > 17) {
   $mydate->modify ("first day of this month")->modify("+ 16 days");
}
else {
   $mydate->modify ("first day of next month")->modify("+ 16 days");

echo $mydate->format('Y-m-d') . "<br/>\r\n";

And, when you test this sort of thing, be sure to test it with days in December and February to ensure the year-rollover and month-rollover logic works correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.