1

I have a php code as shown below in which I am trying to retrieve the last day of next month.

<?php

date_default_timezone_set('America/Toronto');

echo date('l jS \of F Y h:i:s A');

$next_month_last_day  = date('t', strtotime('next month'));  // last day of the next month

print_r("\n");

print_r($next_month_last_day);   // Line A

?>

Problem Statement:

I am wondering what mistake I have done in the php code above because the code at Line A prints 31. It should be printing 30 because the last day of next month (April) is 30.

flash
  • 1,455
  • 11
  • 61
  • 132

5 Answers5

3

Just use

date('d', strtotime('last day of +1 month'));
Dharman
  • 30,962
  • 25
  • 85
  • 135
Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
2

You can use last day of next month

$date = new \DateTime('last day of next month');
echo $date->format('Y-m-d');
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

Another way to go about it is to get the first day of the next month, then use t to format it to the number of days of that month.

echo date("t", strtotime("first day of next month")); // 2021-04-30  10:27:35
aynber
  • 22,380
  • 8
  • 50
  • 63
-1

I had to manually overwrite today's day so DateTime wouldn't skip a month. But it doesn't matter since you only want to know what the next month is.

$dateTime = new DateTime('now', new DateTimeZone("America/Toronto"));
$dateTime->setDate($dateTime->format('Y'), $dateTime->format('m'), 01);

$nextMonth = $dateTime->modify('+1 month');

echo cal_days_in_month(CAL_GREGORIAN, $nextMonth->format('m'), $nextMonth->format('Y'));
Gilly
  • 9,212
  • 5
  • 33
  • 36
-1

Try This

$lastDay = date('t',strtotime('next month'));

 

print_r($lastDay);
Waids
  • 108
  • 1
  • 5