Alias Varghese
Alias Varghese

Reputation: 2170

Converting Hours to Minutes in .NET

I have a time span 2h 30min 22sec.But I need the time bounded to UI in a format 150min 22sec. How it is possible ? any built in function or formatting available?

Upvotes: 2

Views: 4725

Answers (3)

Mike Eason
Mike Eason

Reputation: 9713

As you require the total minutes, you could use a MultiBinding.

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="{}{0}min {1}sec">
            <Binding Path="YourTimeSpan.TotalMinutes" Converter="{StaticResource ObjectToIntegerConverter}"/>
            <Binding Path="YourTimeSpan.Seconds"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

EDIT:

As pointed out in the comments, you will have to convert the TotalMinutes to an integer, to do this, you can use an IValueConverter.

public class ObjectToIntegerConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return System.Convert.ToInt32(value);
    }

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

Don't forget to declare it in your Resources, for example:

<Window
    ...
    xmlns:Converters="clr-namespace:Your.Converters.Namespace">

    <Window.Resources>
        <Converters:ObjectToIntegerConverter x:Key="ObjectToIntegerConverter"/>
    </Window.Resources>

Upvotes: 4

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98810

I'm not familiar on XAML side but you can format your TimeSpan as;

var ts = new TimeSpan(2, 30, 22);

Console.WriteLine(string.Format("{0}min {1}sec", 
                                (int)ts.TotalMinutes,
                                ts.Seconds));

generates

150min 22sec

Upvotes: 3

Luaan
Luaan

Reputation: 63772

Just make your own:

public struct MyTimeSpan
{
  private readonly TimeSpan _data;

  public MyTimeSpan(TimeSpan data)
  {
    _data = data;
  }

  public override string ToString()
  {
    return string.Format("{0:f0}min {1}sec", _data.TotalMinutes, _data.Seconds);
  }
}

Upvotes: 1

Related Questions