以格式“HH:mm:ss,fff”计算字符串中的总秒数(Calculate total seconds from string in format “HH:mm:ss,fff”)

编程入门 行业动态 更新时间:2024-10-23 01:43:41
以格式“HH:mm:ss,fff”计算字符串中的总秒数(Calculate total seconds from string in format “HH:mm:ss,fff”)

在PowerShell V2中,我想计算给定字符串的总秒数和毫秒数。 我的字符串是00:03:56,908 ,所需的输出是236.908

我的工作,但尴尬的代码是

$a = "00:03:56,908" $a = [datetime]::ParseExact($a,"HH:mm:ss,fff",$null) [string]($a.Hour*3600 + $a.Minute*60 + $a.Second) +"."+ [string]$a.Millisecond

有一个更聪明/更短的方式来实现这一目标吗?


我发现的只有TimeSpan对象的.totalseconds。 但是这个代码在我的尝试中甚至更长

In PowerShell V2, I want to calculate the total seconds and milliseconds of a given string. My string is 00:03:56,908 and the desired output would be 236.908

My working, but awkward code is

$a = "00:03:56,908" $a = [datetime]::ParseExact($a,"HH:mm:ss,fff",$null) [string]($a.Hour*3600 + $a.Minute*60 + $a.Second) +"."+ [string]$a.Millisecond

Is there a smarter / shorter way to achieve this?


All I found was .totalseconds from a TimeSpan object. But this code was even longer in my attempt

最满意答案

.NET版本4.0以前的TimeSpan类的问题在于它没有很好地处理不同的文化或格式化字符串。 考虑到你的字符串有一个逗号而不是一个句点,如果我们想解析它到一个时间段,我们将不得不改变,但我认为这仍然是最好的方法。

$timeString = "00:03:56,908" $timeStringWithPeriod = $timeString.Replace(",",".") $timespan = [TimeSpan]::Parse($timestringWithPeriod) $totalSeconds = $timespan.TotalSeconds

The problem with the TimeSpan class in .NET versions earlier than 4.0 is that it's not handling different cultures or formatting strings very well. Given that your string has a comma instead of a period, we'll have to change that if we want to parse it to a timespan, but I think that's still the best way to go at it.

$timeString = "00:03:56,908" $timeStringWithPeriod = $timeString.Replace(",",".") $timespan = [TimeSpan]::Parse($timestringWithPeriod) $totalSeconds = $timespan.TotalSeconds

更多推荐

本文发布于:2023-07-31 01:41:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340478.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   格式   ss   fff   mm

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!