Jackz
Jackz

Reputation: 151

Converter --> Convert DateTime to HH:mm:ss format

I am trying to display a hh:mm:ss format but i always get the full date displayed.

Is there something wrong / missing from my Convertor Class / Dependency Properties? I only receive the Datetime.now display, how to change this to 00:00:00?

What i actually want is to display 00:00:00 as initialization. Later it increments trough timers.

XAML:

<ListBox.ItemTemplate>
<DataTemplate>
    DownTime="{Binding DownTime, Converter={StaticResource  DateTimeConverter}, 
    ConverterParameter=\{0:hh:mm:ss\}}
</DataTemplate>
</ListBox.ItemTemplate>

Dependency Properties:

public static readonly DependencyProperty DownTimeProperty =
    DependencyProperty.Register("DownTime", typeof(DateTime), typeof(RegistrationButton), new UIPropertyMetadata(DateTime.Now));

public DateTime DownTime
    {
        get { return (DateTime)GetValue(DownTimestandProperty); }
        set { SetValue(DownTimeProperty, value); }
    }

Convertor class:

    [ValueConversion(typeof(DateTime), typeof(String))]
public class DateTimeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        DateTime dt = (DateTime)value;
        return dt;

    }

    // No need to implement converting back on a one-way binding 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string strValue = value as string;
        DateTime resultDateTime;
        if (DateTime.TryParse(strValue, out resultDateTime))
        {
            return resultDateTime;
        }
        return DependencyProperty.UnsetValue;
    }
}

Thanks.

Upvotes: 0

Views: 2236

Answers (1)

dcarneiro
dcarneiro

Reputation: 7180

You can just use StringFormat

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

EDIT

DateTime Represents an instant in time, typically expressed as a date and time of day.

TimeSpan Represents a time interval.

They have many similar methods, especially the ones to add or remove hours/mins/seconds and I think that's what you want for this case.

Upvotes: 4

Related Questions