Convert time to seconds

2019-02-12 14:48发布

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

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, etc.

if (HourMinuteToDecimal("01:30") > HourMinuteToDecimal("23:30")) { .. } 

This will not work.

标签: php time
4条回答
太酷不给撩
2楼-- · 2019-02-12 14:59

PHP5.3

$formattedTime = '00:01:38';
$seconds = strtotime('1970-01-01 ' . $formattedTime . 'GMT')
查看更多
Melony?
3楼-- · 2019-02-12 15:00

You can compare objects of type time using the standard <, >, == operators. Use strtotime to convert the string to time, then compare.

查看更多
走好不送
4楼-- · 2019-02-12 15:06

You seem to be asking contradicting things.

  • You want to convert a time in HH:MM into seconds.
  • But then you want to "compare" the result from different times, as if they had dates attached.

If you want to allow HourMinuteToDecimal("01:30") > HourMinuteToDecimal("23:30") to be true without a date, then, well, any comparison will return true.

If you want to do this properly, include the date (YYYY-MM-DD HH:MM:SS) and use strtotime in PHP to get the number of seconds since the UNIX epoch.


Also, your function returns minutes, not seconds.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-02-12 15:19

To convert function:

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'];

}

Write on the fly, no tested :-P

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.

etc..

查看更多
登录 后发表回答