获取当月两个日期之间的天数

时间:2021-04-14 20:52:47

标签: php php-5.4

我必须计算两个日期之间经过的天数,但我需要拆分每个月的天数差异并只显示当月经过的天数。这是计算员工休假时间所必需的。

注意:我需要在 PHP 5.4 上做这个。 例如,我将使用这两个日期和当前月份:

<?php
CurrentMonth="04";
FirstDate="2021-03-28";
SecondDate="2021-04-15";
?>

因此,对于此示例,总天数差异为 18 天,但我只需要返回当前月份“04”中过去的 15 天。

有什么建议吗? 提前致谢。

2 个答案:

答案 0 :(得分:1)

只是对 Pablo 的代码做了一点修改,如果当前月份在第一个日期,则获取天数差异:

<?php
$currentMonth = '04';
$firstDate = new DateTime('2021-03-28');
$lastDay= new DateTime($firstDate->format( 'Y-m-t' )); //last day of $firstDate month
$secondDate = new DateTime('2021-04-15');
$firstDay= $secondDate->format( 'Y-m-01' ); //first day of $secondDate month
$firstDayDT = new DateTime($firstDay); //datetime for $firstDay

$firstDateMonth = $firstDate->format('m');
$secondDateMonth = $secondDate->format('m');

if ($currentMonth === $secondDateMonth) {
    $diff = $secondDate->format('j') - $firstDayDT->format('j')+1; //sum +1 day
} else if ($currentMonth === $firstDateMonth) {
    $diff = $lastDay->format('j') - $firstDate->format('j');
};
echo $diff;

如果当前月份是“03”,代码返回3,如果月份是“04”,返回15。

答案 1 :(得分:0)

一个简单问题的简单解决方案:

<div class="category-list__items">
  {% for category in portal.solution_categories%}
    {% for folder in category.folders %}
      {% if folder.articles_count > 0 %} 
          <div  class="category-list-item">
            <a href="{{category.url}}" class="category-list-item__link">
              <div class="category-list-item__content">
                <h3 class="category-list-item__title">{{category.name}}({{ folder.articles_count }})</h3>
              </div>
            </a>
          </div>
         {% break %}
       {% endif %}
     {% endfor %}
   {% endfor %}
</div>

使用当前月份作为变量:

$firstDate = new DateTime('2021-03-28');
$secondDate = new DateTime('2021-04-15');

$diff = $firstDate->format('n') < $secondDate->format('n')
    ? $secondDate->format('j')
    : $secondDate->format('j') - $firstDate->format('j');
相关问题