在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.MillisecondIs 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.TotalSecondsThe 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更多推荐
发布评论