Convert seconds to hh:mm:ss,fff format in PowerShell

powershell, powershell-2.0, windows-7-x64

Solution

In PowerShell 4.0

$s = "7000.6789"
$ts =  [timespan]::fromseconds($s)
("{0:hh\:mm\:ss\,fff}" -f $ts)

Output: `01:56:40,679`

In PowerShell 2.0

$s = "7000.6789"
$ts =  [timespan]::fromseconds($s)
"{0:hh:mm:ss,fff}" -f ([datetime]$ts.Ticks)

Output: `01:56:40,679`

And to go back the other way...

$text = "01:56:40,679"
$textReformat = $text -replace ",","."
$seconds = ([TimeSpan]::Parse($textReformat)).TotalSeconds
$seconds

Output: `7000.679`

Problem

I have a string representing a time in seconds and milliseconds. I want to convert it to a string in the format "hh:mm:ss,fff". My solution still has the flaw that hours less than 10 are shown with one decimal instead of two: ``` PS> $secs = "7000.6789" PS> $ts = [timespan]::fromseconds($s) PS> $res = "$($ts.hours):$($ts.minutes):$($ts.seconds),$($ts.milliseconds)" PS> $res PS> 1:56:40,679 ``` What is the right way to achieve this? I'm sure there is a more elegant way with `-f` and datetime.

Original source