Author Posts

January 1, 2012 at 12:00 am

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:

[quote]
C:\dt11258\ps1>powershell -file .\testdur.ps1
01:02:03
01:02:03:01:02:03:01:02:03
[/quote]

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))
01:02:03
01]

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.

[quote]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
Name

“c”
Constant format (not culture sensitive.

[-]d.hh]

“g”
General short format (culture sensitive)

[-]d.hh]

“G”
General long format (culture sensitive)

[-]d.:hh:mm:ss.fffffff

[/quote]

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.