【问题标题】:Get the number of days between two dates just for the current month仅获取当前月份的两个日期之间的天数
【发布时间】:2021-07-09 22:19:35
【问题描述】:

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

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

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

所以,对于这个例子,总天数是 18 天,但我只需要返回当月“04”过去的 15 天。

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

【问题讨论】:

  • holidays time 与问题有何关系?它只是当月的天数吗?
  • 是的,第一个日期是假期的开始时间,第二个日期是假期的结束时间。
  • 不确定我是否遵循,假期通常是 1 天。就像圣诞节是 12 月 25 日一样,所以有些人不希望在假期时间计算中使用它。这是你的意思还是别的什么?
  • 对不起,我指的是假期
  • 如果你 just need the days passed in the current month 为什么第一个日期/范围很重要?

标签: php php-5.4


【解决方案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。

【讨论】:

    【解决方案2】:

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

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

    使用当前月份作为变量:

    $currentMonth = '04';
    $firstDate = new DateTime('2021-03-28');
    $secondDate = new DateTime('2021-04-15');
    
    $firstDateMonth = $firstDate->format('m');
    $secondDateMonth = $secondDate->format('m');
    
    if ($currentMonth === $firstDateMonth && $currentMonth === $secondDateMonth) {
        $diff = $secondDate->format('j') - $firstDate->format('j');
    } else {
        $diff = $currentMonth === $secondDateMonth
            ? $secondDate->format('j')
            : null;
    }
    

    【讨论】:

    • 此代码无法正常工作。例如,对于第 4 个月和从 2021-03-28 到 2021-05-15 的时间间隔,返回 null 作为结果。
    • 看看下面的答案。仅适用于下个月或上个月。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2019-06-05
    • 1970-01-01
    相关资源
    最近更新 更多