Share via


WPF: Tips - StringFormat on Timespan

The way you use StringFormat on Timespan is similar but significantly different from DateTime.


Formatting DateTime

If you wanted to use StringFormat on a binding to a DateTime Target property you use the Custom Date and Time strings:

<TextBlock Text="{Binding MyDateTime, StringFormat={}{0:hh:mm:ss} }"/>

If the target property was instead a TimeSpan and you used that StringFormat then you would see no output at all.
Pretty confusing, but perhaps not a total surprise when you consider that DateTime and TimeSpan are two different types.

So how do you deal with Timespan then?

Option 1

You can sort of split the Timespan up into the hours, minutes and seconds pieces:

<TextBlock Text="{Binding TS, StringFormat={}{0:hh}:{0:mm}:{0:ss}}"/>

There is a gotcha lurking in the shadows with this technique.
If you try that with tenths of seconds:

<TextBlock Text="{Binding TS, StringFormat={}{0:hh}:{0:mm}:{0:ss}:{0:f} }"/>

You will see no output at all.
Leaving you with.

Option 2

There's a somewhat unusual slash rich escape sequence you can use:

<TextBlock Text="{Binding TS, StringFormat={}{0:hh\\:mm\\:ss\\:f} }"/>

That works with tenths of seconds as well,

And that's it.  
A fairly short tip, but this is something which could see you wasting a fair bit of time because TimeSpan is somewhat unusual.

Conclusion

You will probably relatively rarely want to display a Timespan on screen.  On those occasions you do so, try and remember this tip before you get no output.
Or after ;^)

See Also

This article is part of the WPF Tips Series, if WPF is your area of interest then you will probably find other useful articles there.