需要PHP日期高级和棘手的编码

时间:2016-07-30 18:15:04

标签: php datetime

请先尝试了解问题。

我希望PHP代码能够找到php中两个日期(天数)之间的差异,并将结果作为数字/ int值存储在php的变量中

我知道会使用date_diff()函数。但是如何? 我在Windows 7上使用wampserver 2.2 我的PHP版本是5.3.12 请帮忙

3 个答案:

答案 0 :(得分:2)

$date = new DateTime('2014-01-31');

$date2 = new DateTime('2014-02-04');

$diff = date_diff($date, $date2, true);
$difference = $diff->format("%a"); // 4

这将为您提供天数差异。如果你想要的不是几天,你可以在这里看到可能的格式:http://php.net/manual/en/dateinterval.format.php

如您所见,函数date_diff()非常易于使用。它将返回一个DateInterval对象,然后您可以对其进行格式化以获得所需的结果。

答案 1 :(得分:-1)

我能想到的最佳解决方案是将日期转换为timestamp然后获得差异。一个例子是: -

$date1 = date('Y-m-d H:i:s');
$date2 = date('Y-m-d H:i:s'); //I know it's same, it will be different in your case.
//conver it to timestamp now
$date1_timestamp = strtotime($date1);
$date2_timestamp = strtotime($date2);
//calculate difference.
$difference = $date2_timestamp - $date2_timestamp;
//the difference variable holds an int value.
//however, if you want to convert it back to readable date, you can do it like this
$difference_readable_date = date('m/d/Y', $difference);

答案 2 :(得分:-1)

我的所有赔率的函数一次或两次,日期或时间戳......

 function time_Diff($time2_, $time1_ = false) {
        $date1 = new \DateTime();
        if ($time1_) {
            $time1 = preg_match('/[-\/]/', $time1_) ? strtotime($time1_) : $time1_;
            $date1->setTimestamp($time1);
        }
        $date2 = new \DateTime();
        $time2 = preg_match('/[-\/]/', $time2_) ? strtotime($time2_) : $time2_;
        $date2->setTimestamp($time2);
        $interval = $date1->diff($date2);
        $diffrent_ = $interval->format('%Y Years %m Months %d Days %H:%I:%S');
        $diffrent = str_replace(['00 Years', ' 0 Months', ' 0 Days', '00:00:00'], '', $diffrent_);
        $returner = str_replace(['01 Years', ' 1 Months', ' 1 Days'], ['01 Year', ' 1 Month', ' 1 Day'], $diffrent);
        return trim($returner);
    }