How to convert a “HH:MM:SS” string to seconds with PHP?

故事扮演 提交于 2019-11-28 03:47:43

问题


Is there a native way of doing "HH:MM:SS" to seconds with PHP 5.3 rather than doing a split on the colon's and multipling out each section the relevant number to calculate the seconds?


For example in Python you can do :

string time = "00:01:05";
double seconds = TimeSpan.Parse(time).TotalSeconds;


回答1:


The quick way:

echo strtotime('01:00:00') - strtotime('TODAY'); // 3600



回答2:


This should do the trick:

list($hours,$mins,$secs) = explode(':',$time);
$seconds = mktime($hours,$mins,$secs) - mktime(0,0,0);



回答3:


I think the easiest method would be to use strtotime() function:

$time = '21:30:10';
$seconds = strtotime("1970-01-01 $time UTC");
echo $seconds;

demo


Function date_parse() can also be used for parsing date and time:

$time = '21:30:10';
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

demo




回答4:


Unfortunately not - as PHP isn't strongly typed there's no concept of a time type and hence no means to convert between such a string and a "seconds" value.

As such, in practice people often split the string and multiply out each section as you mentioned.



来源:https://stackoverflow.com/questions/4605117/how-to-convert-a-hhmmss-string-to-seconds-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!