2012-02-13 55 views
1

我在数据库如何做到这一点倒计时

我得到的当前日期的最后一天,让我们假设是UTC

class Datecalc 
{ 

    public $year; 
    public $month; 
    public $day; 
    public $hour; 
    public $min; 
    public $sec; 

    function diff($start,$end = false) 
    { 
     if($start > $end) 
     { 
      $this->day = 0; 
      $this->hour = "00"; 
      $this->min = "00"; 
      $this->sec = "00"; 
      return false; 

     } 
     if(!$end) { $end = time(); } 
     if(!is_numeric($start) || !is_numeric($end)) { return false; } 
     $start = date('Y-m-d H:i:s',$start); 
     $end = date('Y-m-d H:i:s',$end); 
     $d_start = new DateTime($start); 
     $d_end  = new DateTime($end); 
     $diff = $d_start->diff($d_end); 

     $this->year = $diff->format('%y'); 
     $this->month = $diff->format('%m'); 
     $this->day  = $diff->format('%d'); 
     $this->hour  = $diff->format('%H'); 
     $this->min  = $diff->format('%I'); 
     $this->sec  = $diff->format('%S'); 

     return true; 
    } 

} 

我用这个功能来计算时间差,但问题是我不能把天数计为99,而当日期是00:00:00,天-1,它的设置为98和时间23:59:59,在这个代码中它的一切都很好,但是如果天数高于30,重置为01,我想你明白我想说什么,请帮助!

换句话说

我需要单独算日子,并需要绑定到天

+0

它总是一个好主意,做日期计算与时间戳,因为你只有一个数字来处理,并可以转换时间戳后计算适当的天/月/任何字符串。 – Corubba 2012-02-13 15:09:47

+0

将您的日期转换为EPOC标准,做差异,然后手动将其转换为月/日等。 – Mikhail 2012-02-13 15:13:18

+0

哦,男士,我真的很困惑,你能给我一个帮助我理解的小例子吗? – 2012-02-13 15:14:58

回答

1

您使用的方法永远不会让你得到天数> 30,因为高于30的任何天将被转换的时间其他月份...

这可能是你最好的办法:
http://www.prettyscripts.com/code/php/php-date-difference-in-days
或者
http://www.bizinfosys.com/php/date-difference.html
(简单的谷歌搜索BTW ...)

+0

我已经搜索了很长时间,我已经创建了一个计算日期的脚本,但我该如何将时间绑定到那些日子,因为当时间变为00:00:00时,日子仍然如此 – 2012-02-13 15:23:54

+0

函数dateDiff($ d1,$ d2){ //返回两个日期之间的天数: return round(abs(strtotime($ d1)-strtotime($ d2))/ 86400); } //结束函数dateDiff好吧我有这个脚本,但我怎么能绑定实时???,当时间设置为00:00:00将天倒数? – 2012-02-13 15:24:38

+0

非常感谢你! – 2012-02-13 15:50:35

1

首先,在检查$ start是否大于$ end之前,您应该检查$ end是否为false。

也就是说,diff方法返回一个DateInterval对象(http://us.php.net/manual/en/class.dateinterval.php),它具有多个选项,包括日期以及年,月,日等。您可能想要使用已经由diff方法返回的内容,而不是格式化函数。

$diff = $d_start->diff($d_end); 
echo 'Total days difference: '.$diff->days; 
echo 'Year, Month, Days, time difference: '. 
$diff->y.' y, '.$diff->m.' m, '.$diff->d.' d, '.$diff->h.' h, '.$diff->i.' m, '.$diff->s.' s, '; 
+0

非常感谢你的这篇文章,真的很有帮助 – 2012-02-13 16:16:53