[英]Get the number of days between two dates just for the current month
我必须计算两个日期之间经过的天数,但我需要拆分每月的天数差异并只显示当前月份经过的天数。 这是计算员工休假时间所必需的。
注意:我需要在 PHP 5.4 上进行此操作。 例如,我将使用这两个日期和当前月份:
<?php
CurrentMonth="04";
FirstDate="2021-03-28";
SecondDate="2021-04-15";
?>
所以,对于这个例子,总天数是 18 天,但我只需要返回当月“04”过去的 15 天。
有什么建议么? 提前致谢。
如果当前月份在第一个日期,只需对 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。
一个简单问题的简单解决方案:
$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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.