How to Format Timespan in Xaml

How to format TimeSpan in XAML

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>

How to format TimeSpan in wpf (DataGrid)?

i solved the problem! in database i was storing "tiempo" like bigint, so i changed it to nvarchar and making a few fixes it works.
thanks for all!

Format TimeSpan value in xaml

For ContentControl like Label use ContentStringFormat Property with the right Custom TimeSpan Format Strings.

<Label Width="100" ContentStringFormat="Total: {0:hh\:mm\:ss}">
<Label.Content>
<PriorityBinding>
<Binding Path="CurrentTime" IsAsync="True"/>
</PriorityBinding>
</Label.Content>
</Label>

C# WPF datagrid format timespan

Following code has been used in Visual Studio 2015 and have DataGrid with DateTime and TimeSpan columns with defined format.

For date following string is used "yyyy-MM-dd"
while for time string "mm\:ss" is used (notice double back slash)

public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();

dataGrid = new DataGrid();

var stackPanel = new StackPanel { Orientation = Orientation.Vertical };
stackPanel.Children.Add(dataGrid);

Content = stackPanel;

Rnd = new Random();
Now = DateTime.Now;
Counter = 1;

foreach (var song in GetSongs())
dataGrid.Items.Add(song);

// var timeSpanConverter = new TimeSpanConverter();
var titleColumn = new DataGridTextColumn { Header = "Title", Binding = new Binding("Title") };
var authorColumn = new DataGridTextColumn { Header = "Author", Binding = new Binding("Author") };
var albumColumn = new DataGridTextColumn { Header = "Album", Binding = new Binding("Album")};
// var durationColumn = new DataGridTextColumn {Header = "Duration", Binding = new Binding("Duration") { Converter = timeSpanConverter } };
var durationColumn = new DataGridTextColumn { Header = "Duration", Binding = new Binding("Duration") { StringFormat = "mm\\:ss" } };
var releaseColumn = new DataGridTextColumn { Header = "Release", Binding = new Binding("Release") { StringFormat = "yyyy-MM-dd" } };

dataGrid.Columns.Add(titleColumn);
dataGrid.Columns.Add(authorColumn);
dataGrid.Columns.Add(albumColumn);
dataGrid.Columns.Add(durationColumn);
dataGrid.Columns.Add(releaseColumn);
}

private DataGrid dataGrid;

private int? Counter;
private DateTime? Now;
private Random Rnd;

private TimeSpan GetDuration() { return TimeSpan.FromSeconds(30 + Rnd.Next(500)); }
private DateTime GetRelease() { Counter += 1; return Now.Value.AddMilliseconds(Counter.Value); }
private string GetTitle() { return $"Title {Counter}"; }
private string GetAlbum() { return $"Album {Counter}"; }
private string GetAuthor() { return $"Author {Counter}"; }

private IList<Song> GetSongs()
{
var list = new List<Song>();

for(var i = 0; i < 1000; i++)
list.Add(new Song() {
Title = GetTitle(),
Album = GetAlbum(),
Author = GetAuthor(),
Release = GetRelease(),
Duration = GetDuration()
});
return list;
}
}

public class Song {
public string Title { get; set; }
public string Author { get; set; }
public string Album { get; set; }
public DateTime Release { get; set; }
public TimeSpan Duration { get; set; }
}

public class TimeSpanConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return ((TimeSpan)value).ToString("mm\\:ss");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}

In case if approach with StringFormat is not working (which should not be the case) you can try approach with Converter (commented in code for Duration column)

WPF Data Binding - Custom Format for TimeSpan Object

You can use StringFormat={}{0:h}. but Timespan format doesn't work like Datetime. You can achieve following way.

  1. Convert Timespan to Datetime
DateTime newElapsedTime = new DateTime() + ElapsedTime;

Then use just like that

<TextBlock Text="{Binding Path=newElapsedTime, StringFormat={}{0:HH}h {0:mm}m {0:ss}s }" />

Or


  1. Write your own Converter
public class TimeSpanFormatter:IValueConverter
{

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var ts=(TimeSpan)value;
return string.Format("{0}h {1}m {2}s",ts.Hours,ts.Minutes,ts.Seconds);
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

Then use just like that. Declare formatter in Resource section with name TimeSpanFormatter.

<TextBlock Text="{Binding Path=ElapsedTime,Converter={StaticResource TimeSpanFormatter}}"></TextBlock>

How to use TimeSpan string format in code in Xamarin.Forms?

Xamarin Forms uses all the basic string.Format options you would normally use. So for a datetime the stringFormat variable would look like this:

"{0:MM/dd/yy H:mm:ss zzz}"

The additional pair of brackets in your format string seem out of place to me. You could try the following for what you're trying to achieve here:

@"{0:hh\:mm}"

TimeSpan string format in Windows Phone XAML

I ended up using a workaround.

<TextBlock Text="{Binding DurationStr}" />

With a new property in the view-model:

public string DurationStr
{
get { return Duration.ToString(@"m\:ss"); }
}

public TimeSpan Duration
{
get { return _duration; }
set
{
_duration = value;
RaisePropertyChanged("Duration");
RaisePropertyChanged("DurationStr");
}
}
private TimeSpan _duration;


Related Topics



Leave a reply



Submit