在php中将字符串转换为时间

时间:2011-11-11 17:48:05

标签: php date

如何在PHP中将"2011-11-03T17:27:56Z"转换为时间。

我希望与当前时间有所不同。

即。如果与当前时间的时差是10分钟,我想要10分钟。如果它是1天,那么我想要1天。

4 个答案:

答案 0 :(得分:7)

这个小片段将为您提供从现在到给定日期之间的秒数差异。

$dateString = "2011-11-03T17:27:56Z";
$date = strtotime($dateString);
$diff = time() - $date;
echo $diff;

要为其提供您要求的特定格式,可以使用我发现的here以下功能:

function time_diff($s) { 
    $m = 0; $hr = 0; $d = 0; $td = "now";
    if ($s > 59) { 
        $m = (int)($s/60); 
        $s = $s-($m*60); // sec left over 
        $td = "$m min"; 
    } 
    if ($m > 59) { 
        $hr = (int)($m / 60); 
        $m = $m - ($hr*60); // min left over 
        $td = "$hr hr"; 
        if ($hr > 1) {
            $td .= "s";
        }
        if ($m > 0) {
            $td .= ", $m min";
        }
    } 
    if ($hr > 23) { 
        $d = (int) ($hr / 24); 
        $hr = $hr-($d*24); // hr left over 
        $td = "$d day"; 
        if ($d > 1) {
            $td .= "s";
        }
        if ($d < 3) { 
            if ($hr > 0) {
                $td .= ", $hr hr";
            }
            if ($hr > 1) {
                $td .= "s";
            }
        } 
    } 
    return $td; 
} 

结合这两者就是你得到的:

$dateString = "2011-11-03T17:27:56Z";
$date = strtotime($dateString);
$diff = time() - $date;
echo time_diff($diff);

输出:

  

8天

答案 1 :(得分:3)

$diffInSecs = time() - strtotime('2011-11-03T17:27:56Z');

答案 2 :(得分:3)

工作示例:(codepad here

<?php

$time_str = "2011-11-03T17:27:56Z";

//echo date('d/m/y H:i:s', strtotime($time_str));
$diff = abs(strtotime("now") - strtotime($time_str)); 

$years   = floor($diff / (365*60*60*24)); 
$months  = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); 
$days    = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$hours   = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60)); 
$minuts  = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60); 
$seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60)); 
printf("%d years, %d months, %d days, %d hours, %d minuts\n, %d seconds\n", $years, $months, $days, $hours, $minuts, $seconds);

(时间差异在这里:How to calculate the difference between two dates using PHP?

答案 3 :(得分:2)

我相信你想要strtotime()功能:

$some_time = strtotime("2011-11-03T17:27:56Z");//outputs a UNIX TIMESTAMP
$time_diff = (time() - $some_time);
if ($time_diff > 86400) {
    echo round($time_diff / 86400) . " days";
} else if ($time_diff > 3600) {
    echo round($time_diff / 3600) . " hours";
} else {
    echo round($time_diff / 60) . " minutes";
}

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

  

该函数需要一个包含英文日期的字符串   格式并将尝试将该格式解析为Unix时间戳