You could just use the ToString
method on the TimeSpan object and specify the format you want to use. Either use one of the standard timespan formats or use a custom timespan format. For example, the following custom format gives the output you want:
$ts = [timespan]::fromseconds("7000.6789")
$ts.ToString("hh\:mm\:ss\,fff")
This will output
01:56:40,679
Update: Updating to provide functions working in PowerShell v2
The above solution works well in PowerShell v4, but not in v2 (since the TimeSpan.ToString(string)
method wasn't added until .NET Framework 4).
In v2 I guess you'll have to either create the string manually (like you are doing in the question) or doing an ordinary ToString()
and manipulate the string. I suggest the former. Here's a function which works fine for that:
function Format-TimeSpan
{
PARAM (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[TimeSpan]$TimeSpan
)
#Current implementation doesn't handle days.
#By including the delimiters in the formatting string it's easier when we contatenate in the end
$hours = $TimeSpan.Hours.ToString("00")
$minutes = $TimeSpan.Minutes.ToString("\:00")
$seconds = $TimeSpan.Seconds.ToString("\:00")
$milliseconds = $TimeSpan.Milliseconds.ToString("\,000")
Write-Output ($hours + $minutes + $seconds + $milliseconds)
}
Testing it using
$ts = [timespan]::fromseconds("7000.6789")
Format-TimeSpan -TimeSpan $ts
$ts | Format-TimeSpan
Yields the following output:
01:56:40,679
01:56:40,679
$res.ToString()
not fill your requirements? It does skip milliseconds if there are no relevant digits and it does append days if the hours would otherwise be higher than 23, which might not suit you. If that doesn't work, look into theTimeSpan.ToString(string)
method, which takes a format string. The format string can either be a standard timespan format or a custom timespan format. – Suggestive