Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format TimeSpan in XAML

I am trying to format a textblock which is bound to a TimeSpan property. It works if the property is of type DateTime but it fails if it is a TimeSpan. I can get it done using a converter. But I am trying to find out if there is any alternatives.

Sample Code:

public TimeSpan MyTime { get; set; }  public Window2() {     InitializeComponent();     MyTime = DateTime.Now.TimeOfDay;     DataContext = this; } 

Xaml

<TextBlock Text="{Binding MyTime,StringFormat=HH:mm}"/> 

I am expecting the textblock to show only hours and mintes. But it is showing as:

19:10:46.8048860

like image 237
biju Avatar asked Dec 30 '10 13:12

biju


People also ask

What is the format of a TimeSpan?

"c" is the default TimeSpan format string; the TimeSpan. ToString() method formats a time interval value by using the "c" format string. TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.

What is the format of TimeSpan in C#?

You can format a TimeSpan in the hh: mm: ss format in C#.


2 Answers

The format string is intended to work on a DateTime, not a TimeSpan.

You could change your code to work with DateTime.Now instead. Your xaml is fine:

<TextBlock Text="{Binding MyTime,StringFormat=HH:mm}"/> 

Update

And from .Net 4 format a TimeSpan as follows:

<TextBlock Text="{Binding MyTime,StringFormat=hh\\:mm}"/> 
like image 189
Tim Lloyd Avatar answered Sep 19 '22 01:09

Tim Lloyd


In .NET 3.5 you could use a MultiBinding instead

<TextBlock>     <TextBlock.Text>         <MultiBinding StringFormat="{}{0}:{1}">             <Binding Path="MyTime.Hours"/>             <Binding Path="MyTime.Minutes"/>         </MultiBinding>     </TextBlock.Text> </TextBlock> 

Update
To answer the comments.

To make sure you output 2 digits even if hours or minutes is 0-9 you can use {0:00} instead of {0}. This will make sure the output for the time 12:01 is 12:01 instead of 12:1.
If you want to output 01:01 as 1:01 use StringFormat="{}{0}:{1:00}"

And Conditional formatting can be used to remove the negative sign for minutes. Instead of {1:00} we can use {1:00;00}

<TextBlock>     <TextBlock.Text>         <MultiBinding StringFormat="{}{0:00}:{1:00;00}">             <Binding Path="MyTime.Hours" />             <Binding Path="MyTime.Minutes" />         </MultiBinding>     </TextBlock.Text> </TextBlock> 
like image 26
Fredrik Hedblad Avatar answered Sep 18 '22 01:09

Fredrik Hedblad