Formatting a duration

Welcome Forums General PowerShell Q&A Formatting a duration

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 7 years, 2 months ago.

  • Author
  • #5881

    Points: 0
    Rank: Member

    by gbritton at 2013-05-02 06:11:04

    I have a little script:

    [code2=powershell]$start = Get-Date
    $end = $start.addhours(1).addminutes(2).addseconds(3)
    $duration = $end – $start

    Write-Host $("{0:c}" -f ($end-$start))
    Write-Host $("{0:hh}:{0:mm}:{0:ss}" -f ($end-$start))[/code2]

    that I'm using to see how to format durations. When I run it, I don't get the results I expected:

    C:\dt11258\ps1>powershell -file .\testdur.ps1

    I expected the second line to look just like the first one. Why does the second line not respect the formatting I specified?

    by poshoholic at 2013-05-02 06:20:45

    You should do it like this instead:
    Write-Host $("{0:hh\:mm\:ss}" -f ($end-$start))
    The backslashes are required to escape the colon character which has special meaning in format strings.

    by poshoholic at 2013-05-02 06:25:31

    Oh, and to answer your question, I'm not sure. I ran your script and it worked fine on my system. I'm using PowerShell 3 though. Perhaps if you're using PowerShell 2 there is a bug? Regardless, I think the example I replied with is a cleaner approach, using a format input once with the entire format specified for that input.

    by mjolinor at 2013-05-02 06:26:34

    I can't reproduce that result:

    $start = Get-Date
    $end = $start.addhours(1).addminutes(2).addseconds(3)
    $duration = $end - $start
    Write-Host $("{0:c}" -f ($end-$start))
    Write-Host $("{0:hh}:{0:mm}:{0:ss}" -f ($end-$start))

    by gbritton at 2013-05-02 08:05:56

    I wonder if its a PowerShell 2.0 problem (I'm still on Windows XP and it looks like I will be for quite some time)?

    by BustedFlush at 2013-05-02 08:42:08

    I can't help you there, on PS3 here too, but in case anyone else is totally confused like I was by the first example {0:c} I found the answer on a "Hey, Scripting Guy" post.

    The easiest way to use the standard TimeSpan format strings is to combine them with composite formatting. When I do this, it provides three formats. The formats are shown in the following table.

    Format Specifier

    Constant format (not culture sensitive.


    General short format (culture sensitive)


    General long format (culture sensitive)


    by gbritton at 2013-05-02 10:04:46

    Yeah, the only think not clear is why [fffffff] is in brackets. Does it display or not? Sometimes I have seen it display, other times not. I can't find the rules for that though.

The topic ‘Formatting a duration’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort