加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 将时间转换为秒

发布时间:2020-12-13 13:15:29 所属栏目:PHP教程 来源:网络整理
导读:什么最好的方式转换24小时的时间到秒,所以它可以用于比较if语句.. function HourMinuteToDecimal($hour_minute) { $t = explode(':',$hour_minute); return $t[0] * 60 + $t[1];}echo HourMinuteToDecimal("23:30");return 1410 如果您尝试将午夜时间(00:00)
什么最好的方式转换24小时的时间到秒,所以它可以用于比较if语句..
function HourMinuteToDecimal($hour_minute) {
        $t = explode(':',$hour_minute);
        return $t[0] * 60 + $t[1];
}

echo HourMinuteToDecimal("23:30");
return 1410

如果您尝试将午夜时间(00:00)转换为秒,则无法正常工作.这是什么解决方案?

00:00,00:30,01:00,01:30等

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

所以,你可以使用strtotime来使用一个标准运算符(==<> =< =!=等)来转换unix时间戳和comparte中的格式日期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.

等等..

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读