Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate number of days in each month in php

Tags:

php

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)');
like image 852
vivek raj Avatar asked Jun 22 '17 06:06

vivek raj


3 Answers

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

like image 180
Mayank Pandeyz Avatar answered Oct 19 '22 10:10

Mayank Pandeyz


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.";
}
like image 26
TripleDeal Avatar answered Oct 19 '22 11:10

TripleDeal


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)');
    }
?>
like image 1
Jaydeep Mor Avatar answered Oct 19 '22 10:10

Jaydeep Mor