Question

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

Était-ce utile?

La solution

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

Autres conseils

I wouldn't shy away from TotalSeconds, it can be useful in this circumstance... and reasonably short, if you just extract that property:

PS C:\> $a = "00:03:56,908"
PS C:\> $a = [datetime]::ParseExact($a,"HH:mm:ss,fff",$null)
PS C:\> (New-TimeSpan -Start (Get-Date).Date -End $a).TotalSeconds
236.908

Putting New-TimeSpan in parenthesis allows us to evaluate that statement first, and then to extract TotalSeconds afterwards. Using (Get-Date).Date is important because it defines midnight, and since you converted $a to a DateTime where the date is today, we need to use midnight today as our Start time.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top