• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Formatting TimeSpan to eliminate partial seconds

F
#1
What am I doing wrong below because no matter what I try in the way of
"normal" formatting, I always get 23:59:59.9999 unless I forcibly remove via
substring() the part I don't want? You'd think the straight forward approach
would work, but for some reason, perhaps beause the object is of type
TimeSpan, PowerShell chokes on it.

# demonstrate PowerShell TimeSpan formatting bug
[datetime] $today = [System.DateTime]::Today
[datetime] $tomorrow = $today.AddDays(1).AddSeconds(-1).AddMilliseconds(-1)
[TimeSpan] $elapsed = New-TimeSpan -Start $today -End $tomorrow
Write-Host $elapsed
# next line fails to produce desired output of just hours,minutes,second (no
partial seconds)
[string] $ts = "{0:hh:mm:ss}" -f $elapsed
Write-Host $ts
# next line fails to produce desired output of just hours,minutes,second (no
partial seconds)
[string] $kludge = [System.String]::Format("{0:hh:mm:ss}", $elapsed)
Write-Host $kludge
# have to forceibly trim unwanted portion of string to get desired output -
why ?
[string] $desired = $ts.Substring(0, 8)
Write-Host $desired
 

My Computer

R

Robert Robelo

#2
Not a bug.
There are no custom/standard format strings for TimeSpan like there are for DateTime.

# you would have to get the desired TimeSpan values to the Format operator
'{0:00}:{1:00}:{2:00}' -f $elapsed.Hours, $elapsed.Minutes, elapsed.Seconds
'{0:00}:{1:00}:{2:00}' -f ($elapsed | % {$_.Hours, $_.Minutes, $_.Seconds})

# or, like String's Substring Method, trim it with the Replace operator
$elapsed -replace '\.\d+$'

--
Robert
 

My Computer