5

need to calculate the number of days from current date to 27th of each month in PHP In below code, it's calculating correctly for current month but if the current date is 28th it should calculate for next month.

$year = date("y");
$month = date("m");
$day = '27';

$current_date = new DateTime(date('Y-m-d'), new DateTimeZone('Asia/Dhaka'));
$end_date = new DateTime("$year-$month-$day", new DateTimeZone('Asia/Dhaka'));
$interval = $current_date->diff($end_date);
echo $interval->format('%a day(s)');
vivek raj
  • 229
  • 1
  • 3
  • 8
  • 1
    Possible duplicate of [Finding the number of days between two dates](https://stackoverflow.com/questions/2040560/finding-the-number-of-days-between-two-dates) – Anoop Toffy Jun 22 '17 at 06:56

5 Answers5

5

Try php cal_days_in_month function

cal_days_in_month — Return the number of days in a month for a given year and calendar

Ex:

$number = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There were {$number} days in August 2003";

Reference

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
2

I wrote this script quick, because I don't have the time to test it yet.

EDIT:

$day = 27;
$today = date('d');

if($today < $day){
    $math = $day - $today;
    echo "There are " . $math . " days left until the 27th.";
} else {
    $diff = date('t') - $today;

    $math = $diff + $day;
    echo "There are " . $math . " days left until the 27th of the next month.";
}
TripleDeal
  • 726
  • 4
  • 14
  • for eg, today's date is 28th which means it goes to the else part and it should show the diff of this month 28th to next month 27 now it's showing the negative value .. :( – vivek raj Jun 22 '17 at 07:08
1

Try below code,

<?php
    $year = date("y");
    $month = date("m");
    $day = '27';

    $current_date = new DateTime(date('Y-m-d'), new DateTimeZone('Asia/Dhaka'));
    $end_date = new DateTime("$year-$month-$day", new DateTimeZone('Asia/Dhaka'));
    if($current_date->getTimestamp()<=$end_date->getTimestamp()){
        $interval = $current_date->diff($end_date);
        echo $interval->format('%a day(s)');
    }
    else{
        $interval = $end_date->diff($current_date);
        echo $interval->format('-%a day(s)');
    }
?>
Jaydeep Mor
  • 1,690
  • 3
  • 21
  • 39
  • for eg, today's date is 28th which means it goes to the else part and it should show the diff of this month 28th to next month 27. – vivek raj Jun 22 '17 at 07:07
  • Yes it goes to else part and display `-1 day(s)`. If you don't want remove else part or set `0` as a interval. – Jaydeep Mor Jun 22 '17 at 07:09
0
$now = time(); // or your date as well
$your_date = strtotime("2010-01-01");
$datediff = $now - $your_date;

echo floor($datediff / (60 * 60 * 24));

Source : Finding the number of days between two dates

Anoop Toffy
  • 918
  • 1
  • 9
  • 22
-1

by this....

<?php
  $d=cal_days_in_month(CAL_GREGORIAN,10,2005);
  echo "There was $d days in October 2005";
?>
GYaN
  • 2,327
  • 4
  • 19
  • 39