将时间转换为秒 [英] Convert time to seconds
本文介绍了将时间转换为秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将24小时制转换为秒制以便可以比较if语句的最佳方法是什么.
What the best way to convert 24 hours time to seconds so it can be used for comparison if statement..
function HourMinuteToDecimal($hour_minute) {
$t = explode(':', $hour_minute);
return $t[0] * 60 + $t[1];
}
echo HourMinuteToDecimal("23:30");
return 1410
如果您尝试将午夜时间(00:00)转换为秒,则将无法使用.有什么解决方案?
If you try to convert midnight time (00:00) to seconds, it will not work. What is the solution to this?
00:00、00:30、01:00、01:30等
00:00, 00:30, 01:00, 01:30, etc.
if (HourMinuteToDecimal("01:30") > HourMinuteToDecimal("23:30")) { .. }
这不起作用.
推荐答案
要转换功能:
function hoursToSecods ($hour) { // $hour must be a string type: "HH:mm:ss"
$parse = array();
if (!preg_match ('#^(?<hours>[\d]{2}):(?<mins>[\d]{2}):(?<secs>[\d]{2})$#',$hour,$parse)) {
// Throw error, exception, etc
throw new RuntimeException ("Hour Format not valid");
}
return (int) $parse['hours'] * 3600 + (int) $parse['mins'] * 60 + (int) $parse['secs'];
}
即时编写,未经测试:-P
Write on the fly, no tested :-P
因此,您可以使用strtotime在Unix时间戳中转换格式日期,并使用标准运算符(==<>> =< =!=等)进行分隔:
so, you can use strtotime to convert the format date in unix timestamp and comparte using a standar operators (== < > >= <= !=, etc) ex:
$t1 = "23:40:12";
$t2 = "17:53:04";
$h1 = strtotime("0000-00-00 $t1");
$h2 = strtotime("0000-00-00 $t2");
$h1 == $h2; // if are equals
$h1 > $h2; // if h1 is mayor at h2
$h1-$h2; // dieference in seconds, etc.
等.
这篇关于将时间转换为秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文