Formatting TimeSpan in PowerShell
powershell parsing

Exploring custom format strings for TimeSpan in PowerShell and C#.
December 4, 2018

TimeSpan is a structure which represents a time interval. Working with TimeSpans in PowerShell can be similar to .NET, or can be made a little easier by using native PowerShell functionality.

In my scenario, I needed to parse a certain point in time, defined by miliseconds, and then output this TimeSpan in a very strict form:

# get from miliseconds:

# to exactly this format:
00:00:00.000 # hours:minutes:seconds.miliseconds (3 numbers)

How to achieve this goal in PowerShell? Let’s explore… (or jump to solution).

> $time = [TimeSpan] 2500045000
> Write-Host $time
> "{0}" -f $time

This isn’t actually that bad - I could go brute and simply cut last three characters from this string, right? Not really. This is what happens when the millisecond part is 0:

> $time = New-TimeSpan -Hours 1 -Minutes 1 -Seconds 1
> "{0}" -f $time

In this case the last part is omitted… Back to the drawing board.

Let’s experiment with timespan format strings:

> "{0:g}" -f $time
> "{0:G}" -f $time

(Note the colon , character as a divider of seconds and milliseconds - that’s because both g/G modifiers are culture-sensitive and my machine is set to the Czech culture.)

Still not good enough. Is there a way to specify my own format string? There is!


It’s not as straightforward as it could be - you have to escape the dividers - but this is how it works:

> "{0:hh\:mm\:ss\.fff}" -f ([TimeSpan] $time)

In C# the trick is to use the @ symbol:

> var time = TimeSpan.FromTicks(2500045000).ToString(@"hh\:mm\:ss\.fff");


> var time = String.Format("{0:" + @"hh\:mm\:ss\.fff" + "}", TimeSpan.FromTicks(2500045000))

And that’s about it ;)

comments powered by Disqus