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:
2500045000

# 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
00:04:10.0045000
> "{0}" -f $time
00:04:10.0045000

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
01:01:01

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:04:10,0045
> "{0:G}" -f $time
0:00:04:10,0045000

(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!

Solution

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)
00:04:10.004

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

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

Or:

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

And that's about it ;)

Found something inaccurate or plain wrong? Was this content helpful to you? Let me know!

šŸ“§ codez@deedx.cz