Windows Vista Forums

Formatting TimeSpan to eliminate partial seconds

  1. #1


    Fred Guest

    Formatting TimeSpan to eliminate partial seconds

    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 System SpecsSystem Spec

  2.   


  3. #2


    Robert Robelo Guest

    Re: Formatting TimeSpan to eliminate partial seconds

    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 System SpecsSystem Spec


Formatting TimeSpan to eliminate partial seconds
Similar Threads
Thread Forum
New-TimeSpan cmdlet PowerShell
Solved Eliminate locking General Discussion
Timespan SMTP Received headers PowerShell
Decode Unusual Timespan .NET General
Compare timespan of Files? .NET General