如何使用 PHP 将“HH:MM:SS”字符串转换为秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4605117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a "HH:MM:SS" string to seconds with PHP?
提问by benjisail
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?
是否有"HH:MM:SS" to seconds
使用 PHP 5.3的本机方式,而不是在冒号上进行拆分并将每个部分乘以相关数字来计算秒数?
For example in Python you can do :
例如在 Python 中,您可以执行以下操作:
string time = "00:01:05";
double seconds = TimeSpan.Parse(time).TotalSeconds;
回答by netcoder
The quick way:
快捷方式:
echo strtotime('01:00:00') - strtotime('TODAY'); // 3600
回答by Spudley
This should do the trick:
这应该可以解决问题:
list($hours,$mins,$secs) = explode(':',$time);
$seconds = mktime($hours,$mins,$secs) - mktime(0,0,0);
回答by Glavi?
I think the easiest methodwould be to use strtotime()
function:
我认为最简单的方法是使用strtotime()
函数:
$time = '21:30:10';
$seconds = strtotime("1970-01-01 $time UTC");
echo $seconds;
Function date_parse()
can also be used for parsing date and time:
函数date_parse()
还可用于解析日期和时间:
$time = '21:30:10';
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
回答by John Parker
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.
不幸的是不是 - 因为 PHP 不是强类型的,所以没有时间类型的概念,因此无法在这样的字符串和“秒”值之间进行转换。
As such, in practice people often split the string and multiply out each section as you mentioned.
因此,在实践中,人们经常像您提到的那样拆分字符串并乘以每个部分。