PHP两个给定日期的日期差异

时间:2015-07-05 06:15:12

标签: php

我想在php中的天数有两个日期差异。以下是在给定日期的剩余时间内完美运行的代码,除了32天。我知道英文中没有32天,但我使用尼泊尔日期存储在数据库中。在尼泊尔日历中也有32天,所以我需要任何人的帮助。

   $dStart = new DateTime('2071-02-32');
   $dEnd  = new DateTime('2071-02-31');
   $dDiff = $dStart->diff($dEnd);
   echo $dDiff->days; //output should come 1 

2 个答案:

答案 0 :(得分:3)

我猜,你可能已经使用转换器(尼泊尔日期到英国日期)来处理它们。如果没有,请使用此Nepali Date Convert

您可以在计算差异之前简单地将尼泊尔日期转换为英语,请参阅下面的示例:

$calendar = new Nepali_Calendar();
$date1 = $calendar->nep_to_eng('2071', '02', '32');
$date2 = $calendar->nep_to_eng('2071', '02', '31');

$dStart = DateTime::createFromFormat('Y-n-j', $date1['year'].'-'.$date1['month'].'-'.$date1['date']);
$dEnd  = DateTime::createFromFormat('Y-n-j', $date2['year'].'-'.$date2['month'].'-'.$date2['date']);
$dDiff = $dStart->diff($dEnd);
echo $dDiff->days;

答案 1 :(得分:0)

下面的代码工作正常:

function diff($time1, $time2, $precision = 6) {
    // If not numeric then convert texts to unix timestamps
    if (! is_int ( $time1 )) {
        $time1 = strtotime ( $time1 );
    }
    if (! is_int ( $time2 )) {
        $time2 = strtotime ( $time2 );
    }

    // If time1 is bigger than time2
    // Then swap time1 and time2
    if ($time1 > $time2) {
        $ttime = $time1;
        $time1 = $time2;
        $time2 = $ttime;
    }

    // Set up intervals and diffs arrays
    $intervals = array (
            'year',
            'month',
            'day',
            'hour',
            'minute',
            'second' 
    );
    $diffs = array ();

    // Loop thru all intervals
    foreach ( $intervals as $interval ) {
        // Set default diff to 0
        $diffs [$interval] = 0;
        // Create temp time from time1 and interval
        $ttime = strtotime ( "+1 " . $interval, $time1 );
        // Loop until temp time is smaller than time2
        while ( $time2 >= $ttime ) {
            $time1 = $ttime;
            $diffs [$interval] ++;
            // Create new temp time from time1 and interval
            $ttime = strtotime ( "+1 " . $interval, $time1 );
        }
    }

    $count = 0;
    $times = array ();
    // Loop thru all diffs
    foreach ( $diffs as $interval => $value ) {
        // Break if we have needed precission
        if ($count >= $precision) {
            break;
        }
        // Add value and interval
        // if value is bigger than 0
        if ($value > 0) {
            // Add s if value is not 1
            if ($value != 1) {
                $interval .= "s";
            }
            // Add value and interval to times array
            $times [] = $value . " " . $interval;
            $count ++;
        }
    }

    // Return string with times
    return implode ( ", ", $times );
}

$startTime = '09-10-2017 10:30 AM';
$endTime = '19-10-2017 04:30PM';
// Run and print diff
echo 'Span: '.diff ( $startTime, $endTime, 6 );