Home > Blockchain >  PHP - Weird behavior when I add a month to the date
PHP - Weird behavior when I add a month to the date

Time:04-14

When I try to add a month to a date and it's the last day of the month, i get this weird behavior

$data = date("Y-m-d", $date);           // $date is 1643583600and $data-> 2022-01-31
$duedate = new DateTime($data);         // $duedate -> "2022-01-31 00:00:00.000000"
$duedate->modify(' 1 month');           // $duedate -> "2022-03-03 00:00:00.000000"
$m = $duedate->format('m');             // $m = 03

However, the problem does not exist if:

  • I want to add a month to 2022-02-28
  • the starting date is not a month end

CodePudding user response:

instead of the last date of the month using the first date of the month.

date("2022-01-01") or date("Y-m-01")

$data = date("2022-01-01");           // $date is 1643583600and $data-> 2022-01-01
$duedate = new DateTime($data);         // $duedate -> "2022-01-01 00:00:00.000000"
$duedate->modify(' 1 month');           // $duedate -> "2022-02-02 00:00:00.000000"
$m = $duedate->format('m');
echo $data." ".$m;

Output

2022-01-01 02

CodePudding user response:

If you're only interested in the number of the next month, you can ask for the first day of next month and you'll be fine.

Note: You can directly insert a timestamp into DateTime if you prepend it with @

$date=1643583600;
$duedate = new DateTime("@$date");
$duedate->modify("first day of next month");
echo $duedate->format('n');

output: 2

CodePudding user response:

This behavior is because of the overflow of no. of days in a month it tries to add. If you wish to get only last day of each month, you can use the t symbol in date like below, which gives you no. of days in a month which is automatically the last day:

<?php

for($i = 1; $i <= 12;   $i){
    echo date("Y-m-t", strtotime(date("Y") . "-". $i. "-01")),PHP_EOL;
}
  • Related