如何将“HH:MM:SS”转换为“HH:MM:SS”用PHP将字符串转换为秒?

发布于 2024-10-10 23:06:37 字数 217 浏览 0 评论 0原文

是否有一种使用 PHP 5.3 将“HH:MM:SS”转换为秒的本机方法,而不是对冒号进行分割并将每个部分的相关数字相乘来计算秒?


例如,在 Python 中你可以这样做:

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

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

徒留西风 2024-10-17 23:06:37

快速方法:

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

The quick way:

echo strtotime('01:00:00') - strtotime('TODAY'); // 3600
猥琐帝 2024-10-17 23:06:37

这应该可以解决问题:

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

This should do the trick:

list($hours,$mins,$secs) = explode(':',$time);
$seconds = mktime($hours,$mins,$secs) - mktime(0,0,0);
落叶缤纷 2024-10-17 23:06:37

我认为最简单的方法是使用strtotime()函数:

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

演示


函数date_parse()也可用于解析日期和时间:

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

demo

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

很糊涂小朋友 2024-10-17 23:06:37

该功能还支持不带小时或分钟的输入

$timeInSecs = function ($tym) {
  $tym = array_reverse(explode(':',$tym));
  $hr = $tym[2] ?? 0;
  $min = $tym[1] ?? 0;
  return $hr*60*60 + $min*60 + $tym[0];
};

echo $timeInSecs('1:1:30') . '<br>'; // output: 3690
echo $timeInSecs('1:30') . '<br>'; // output: 90
echo $timeInSecs('30') . '<br>'; // output: 30

This function also supports input without hour or minute

$timeInSecs = function ($tym) {
  $tym = array_reverse(explode(':',$tym));
  $hr = $tym[2] ?? 0;
  $min = $tym[1] ?? 0;
  return $hr*60*60 + $min*60 + $tym[0];
};

echo $timeInSecs('1:1:30') . '<br>'; // output: 3690
echo $timeInSecs('1:30') . '<br>'; // output: 90
echo $timeInSecs('30') . '<br>'; // output: 30
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文