如何计算php中每个月的天数

时间:2017-06-22 06:45:42

标签: php

需要在PHP中计算从当前日期到每月27日的天数 在下面的代码中,它正确计算当前月份,但如果当前日期是28日,则应计算下个月。

$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)');

5 个答案:

答案 0 :(得分:5)

尝试php cal_days_in_month功能

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

例如:

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

Reference

答案 1 :(得分:2)

我快速编写了这个脚本,因为我还没有时间对它进行测试。

修改

$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.";
}

答案 2 :(得分:1)

尝试以下代码,

<?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)');
    }
?>

答案 3 :(得分:0)

$now = time(); // or your date as well
$your_date = strtotime("2010-01-01");
$datediff = $now - $your_date;

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

来源:Finding the number of days between two dates

答案 4 :(得分:-1)

由此......

<?php
  $d=cal_days_in_month(CAL_GREGORIAN,10,2005);
  echo "There was $d days in October 2005";
?>