2012-11-19 45 views
0

我有一个日期格式为“14/11/2012 4:26:10 PM”从MySQL查询中提取。PHP - TimeSpan From DateTime

我对PHP并不是很有经验,但是如何计算日期“Then”和“Now”之间的简单时间间隔?

并将其格式化为可读的字符串?例如......“1小时,5分钟前”。

我试图寻找一个解决方案,我发现了一个我认为可以工作但它没有考虑AM/PM,所以最终导致一个问题,当我将它转换为时间戳。有人有什么主意吗?

这就是我要做的,但这并不工作这么好:

$time = $row["NotificationSent"];   
      list($day, $month, $year, $hour, $minute) = split('[/ :]', $time); 
      $timestamp = mktime($hour, $minute,0, $month, $day, $year);   
      $j = TimeSince($timestamp); 

的timesince功能,我发现离我使用谷歌是:

function TimeSince($original) // $original should be the original date and time in Unix format 
    { 
     // Common time periods as an array of arrays 
     $periods = array(
      array(60 * 60 * 24 * 365 , 'year'), 
      array(60 * 60 * 24 * 30 , 'month'), 
      array(60 * 60 * 24 * 7, 'week'), 
      array(60 * 60 * 24 , 'day'), 
      array(60 * 60 , 'hour'), 
      array(60 , 'minute'), 
      ); 

     $today = time(); 
     $since = $today - $original; // Find the difference of time between now and the past 

     // Loop around the periods, starting with the biggest 
     for ($i = 0, $j = count($periods); $i < $j; $i++) 
     { 
      $seconds = $periods[$i][0]; 
      $name = $periods[$i][1]; 

      // Find the biggest whole period 
      if (($count = floor($since/$seconds)) != 0) 
      { 
       break; 
      } 
     } 

     $output = ($count == 1) ? '1 '.$name : "$count {$name}s"; 

     if ($i + 1 < $j) 
     { 
      // Retrieving the second relevant period 
      $seconds2 = $periods[$i + 1][0]; 
      $name2 = $periods[$i + 1][1]; 

      // Only show it if it's greater than 0 
      if (($count2 = floor(($since - ($seconds * $count))/$seconds2)) != 0) 
      { 
       $output .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s"; 
      } 
     } 
     return $output; 
    } 

返回结果被格式化为我正在查找的内容,但给出的数字不正确。 “19/11/2012 2:48:53 PM”正在返回“1天,5小时”,但应该是“17小时,32分钟”

任何帮助表示赞赏。

+0

[如何计算使用PHP的两个日期之间的差异?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using- php) – Blazemonger

+0

'mktime'预计24小时格式,当你正在分割文本时,你省略了'PM',因此在50%的情况下预计12h的差异。 –

+0

你可以分享sql查询吗?我想知道你是如何实际存储时间戳记在你的分区 – omercnet

回答

1

如果你有一个人类可读的时间戳,您可以用strtotime()将其转换为Unix时间戳:

http://php.net/manual/en/function.strtotime.php

然后,只需减去time()从该值以获得时间,以秒为以往。

+2

为什么不更现代一点,并使用'DateTime :: createFromFormat'来代替? http://www.php.net/manual/en/datetime.createfromformat.php – techouse

+1

,因为我的是更容易... – Landon

4

见,这就是DateTime对象前来救援:

<?php 

$time = DateTime::createFromFormat("d/m/Y g:i:s A", "14/11/2012 4:26:10 PM");; 
$now = new DateTime; 

$diff = $time->diff($now); 
var_dump($diff); 

你得到的差值正好,你可以在任何你喜欢的方式对其进行格式化。

+0

应该指出,如果你没有设置时区date_default_timezone_set( )'(或其他一些等效的) –

+0

嗯,不是真的:P只是使用'$ now = new DateTime('',new DateTimeZone('Berlin/Europe'));'而不是你不会有任何致命错误 – techouse