2014-02-26 75 views
1

我需要比较两个不同的时间。这两种格式:时间(仅限与非日期)比较

小时:分:秒

他们没有从当前时间回升。所以,没有strtotimeDateTime。我不希望日期以任何方式参与比较。 这里的每个问题都以strtotime作为答案。

我想要比较这两个时间,其中一个是从数据库中摘取(类型为time)&一个我手动给字符串。

例如:$A="00:00:00"(如果可以存储,否则请注意)。

如果有什么办法做到这一点,请你告诉我?Thnxx提前...

+0

您可以使用一个日期在此日期内 – k102

+0

比较倍就像我说的一个一次我给手动。虽然不是一个好的做法,但那段时间将会被硬编码,我需要将它与DB中可能有所不同的时间进行比较。 – Gogo

回答

0

如果时间为24小时格式,你可以简单地通过字符串比较比较吧

$A="00:00:00" 
$B="13:00:00" 

if ($A > $B) { 
    // do stuff 
} 
+0

我从数据库中收到的数据是类型'时间' 所以不能真正比较 – Gogo

+0

我相信当php从您的数据库读取,'时间'类型将自动转换为字符串。正确? – SajithNair

+1

是的,你是好友;) – Gogo

0

,如果你不希望使用strtotimeDateTime我不知道它会为您提供正确的输出因为它会比较字符串或INT值,因此无法计算准确的时间,以便更好地使用PHP的日期和时间函数

For eg: $A="00:00:00" (it will be a string value) 

所以更好的输出将被这两个值使用strtotime()转换,做你的东西

+0

对不起...不能使用它。这将是我最后的手段&将包括字符串拼接 – Gogo

1

你可以使用转换你的时间到秒的功能,然后以此为基础进行结果的比较

function getTimeInSeconds($hours, $minutes, $seconds) { 
    $totalSeconds = 0; 

    //Add the numner of hours in seconds 
    $totalSeconds += ($hours * 60) * 60; 

    //Add the number of minutes in seconds 
    $totalSeconds += $minutes * 60; 

    //Add seconds 
    $totalSeconds += $seconds; 

    return $totalSeconds; 
} 

$firsttime = getTimeInSeconds(8, 30, 14); 
$secondtime = getTimeInSeconds(10, 15, 06); 

//If second time is later than first time 
if($secondtime > $firsttime) 
{ 
} 

//If first time is later than second time 
if($firsttime > $secondtime) 
{ 
} 
+0

谢谢..这也是一个办法 – Gogo

0

你可以只需将秒数乘以并比较即可。

$timebits = explode(':',$A); 
$secondsDB = $timebits[2] + timebits[1]*60 + $timebits[0]*60*60 

然后再比较你的手动时间,以秒为单位。

0

如果您需要比较格式HH:MM:SS是否相等,或者如果一个在另一个之前,并且不想使用strtotime函数,则应将所有转换为秒并将其作为数字进行比较。

简单的例子:

$a="01:30:08"; 
$b="02:20:50"; 

function toseconds($str){ 
    $array = explode(":",$str); 
    $val = $array[0] * 24 * 60; 
    $val += $array[1] * 60; 
    $val += $array[2]; 
    return $val; 
} 

print toseconds($a); // print a 
print " compare to "; 
print toseconds($b); // print b 
print " "; 

if($a > $b){ 
    print "b is before a"; 
}else if ($b > $a){ 
    print "a is before b"; 
}else if($b == $a){ 
    print "a and b are the same time"; 
} 
0

可以在MySQL查询使用CAST()功能

SELECT * FROM table_name WHERE yourcolumn < CAST('05:00:00' AS time) 
+0

只是1个问题给你。你为什么低估了我所有的问题? – Gogo

+0

@shaktimaan如果我是,为什么我再回答你? –

+0

确定无论什么好友...只是记得SO不适合这种有点东西。 &至于你的答案,我已经在问题下面的评论中与k102讨论过了 – Gogo