PHP — 将毫秒转换为小时 : 分钟 : 秒.fractional
我有一个脚本,它接受以秒为单位的值(到秒的小数点后两位):
$seconds_input = 23.75
然后将其转换为毫秒:
$milliseconds = $seconds_input * 1000; // --> 23750
然后我想像这样格式化它:
H:M:S.x // --> 0:0:23.75
其中“x”是秒的分数(但是小数点后还有很多位)。
有什么帮助吗?我似乎无法全神贯注于此。我尝试使用 gmdate() 但它不断减少小数秒。
谢谢。
I've got a script that takes in a value in seconds (to 2 decimal points of fractional seconds):
$seconds_input = 23.75
I then convert it to milliseconds:
$milliseconds = $seconds_input * 1000; // --> 23750
And then I want to format it like so:
H:M:S.x // --> 0:0:23.75
Where 'x' is the fraction of the second (however many places after the decimal there are).
Any help? I can't seem to wrap my mind around this. I tried using gmdate() but it kept lopping off the fractional seconds.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你真的想使用日期函数来做到这一点,你是对的,你必须在外部处理毫秒,仅基于第二时间戳。
你可以这样做:
但要注意小时溢出,如果你的时间超过 24 小时,你可能最终会放弃这些日子。
在你的情况下,我会说你用地板来获取秒数的方法是正确的,然后你可能应该只使用像这样的模算术:
等等..
if you really want to do it using date function you are right, you have to deal with milliseconds externally, is only based on second-timestamps.
you could do something like this:
but be aware of the hour-overflow, if your hours exceed 24 you will probably end up discarding the days.
in your case i would say your approach with floor to get the seconds is correct, and then you should probably just use modulo arithmetics like this:
and so on..
我的可读性要差得多,所以它一定更好。 :p
基本上与@ircmaxell 的版本相同的想法。它确实会修剪尾随的“0”,甚至会跳过最后一个“.”。如果毫秒为 0,则分隔符。
Mine is much less readable, so it must be better. :p
Basically the same idea as @ircmaxell's version. It does trim the trailing '0's and even will skip the last '.' separator if milliseconds are 0.
我的看法
然后是测试
结果
My take
And then the test
which yields
编辑:嗯,我有点仓促了。这是执行您所要求的操作的一种方法:
Edit: Well, I was a bit hasty. Here's one way to do what you're asking: