Forum Xamarin.Forms

How to set time in TimePicker using XAML and converter

DomKapDomKap USMember ✭✭

Hi.
I'm a bit confuse how to set the time in time picker using converter in xaml.

<TimePicker                    
                    x:Name="timePicker" 
                    Time="{Binding AlarmTime, Converter={StaticResource DateToTimeSpanConverter}}"                    
                    PropertyChanged="timePicker_PropertyChanged"                   
                    />

My converter:

 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DateTime dateObj = (DateTime)value;

                TimeSpan time1 = new TimeSpan(dateObj.Hour, dateObj.Minute, 00);

                var time2 = dateObj.TimeOfDay;

                return time2; 
    //or return time1;     
        }

Binding AlarmTime is DateTime object and from that object I would like to get time and set my TimePicker.

In converter I tried do it in two ways.
First option is to create a new TimeSpan and return it.
Second option is return TImeOfDay.

Unfortunately both options don't work. Time always is "00:00".

What do I have to return, to set time?

Best Answer

Answers

  • JorgeDiegoJorgeDiego USMember ✭✭

    Hi @DomKap
    Here you have an example. I´m using two picker to introduce the date and the time.

                        <DatePicker Date="{Binding Fecha, Mode=TwoWay}" />
                        <TimePicker Time="{Binding Hora, Mode=TwoWay, Converter={StaticResource DateTimeToTimeSpanConverter}}" />
    

    This is the converter I´m ussing in the time picker

        public class DateTimeToTimeSpanConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                try
                {
                    DateTime dt = (DateTime)value;
                    TimeSpan? ts = DateTimeConverter.DateTimeToTimeSpan(dt);
                    return ts.GetValueOrDefault(TimeSpan.MinValue);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    return TimeSpan.MinValue;
                }
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                try
                {
                    TimeSpan ts = (TimeSpan)value;
                    DateTime? dt = DateTimeConverter.TimeSpanToDateTime(ts);
                    return dt.GetValueOrDefault(DateTime.MinValue);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    return DateTime.MinValue;
                }
            }
        }   
    
        public static class DateTimeConverter
        {
            public static TimeSpan? DateTimeToTimeSpan(DateTime dt)
            {
                TimeSpan FResult;
                try
                {
                    FResult = dt - dt.Date;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    return null;
                }
    
                return FResult;
            }
    
    
            public static DateTime? TimeSpanToDateTime(TimeSpan ts)
            {
                DateTime? FResult = null;
                try
                {
                    string year = string.Format("{0:0000}", DateTime.MinValue.Date.Year);
                    string month = string.Format("{0:00}", DateTime.MinValue.Date.Month);
                    string day = string.Format("{0:00}", DateTime.MinValue.Date.Day);
    
                    string hours = string.Format("{0:00}", ts.Hours);
                    string minutes = string.Format("{0:00}", ts.Minutes);
                    string seconds = string.Format("{0:00}", ts.Seconds);
    
                    string dSep = "-"; string tSep = ":"; string dtSep = "T";
    
                    // yyyy-mm-ddTHH:mm:ss
                    string dtStr = string.Concat(year, dSep, month, dSep, day, dtSep, hours, tSep, minutes, tSep, seconds);
    
                    DateTime dt;
                    if (DateTime.TryParseExact(dtStr, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out dt))
                    {
                        FResult = dt;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    throw;
                }
    
                return FResult;
            }
    
    
            public static DateTimeOffset? DateTimeToDateTimeOffSet(DateTime dt)
            {
                try
                {
                    return new DateTimeOffset(dt);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    return null;
                }
            }
    
    
            public static DateTime? DateTimeOffSetToDateTime(DateTimeOffset dto)
            {
                try
                {
                    return dto.DateTime;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    return null;
                }
            }
        }
    

    And this is my viewModel code

            private DateTime _fecha;
    
            public DateTime Fecha
            {
                get { return _fecha; }
                set
                {
                    _fecha = new DateTime(value.Year, value.Month, value.Day,
                        Hora.Hour, Hora.Minute, Hora.Second);
                    RaisePropertyChanged();
                }
            }
    
            public DateTime Hora
            {
                get { return _fecha; }
                set
                {
                    _fecha = new DateTime(Fecha.Year, Fecha.Month, Fecha.Day,
                        value.Hour, value.Minute, value.Second);
                    RaisePropertyChanged();
                }
            }
    

    I hope it helps you.
    Best regards

  • DomKapDomKap USMember ✭✭
    edited August 2017

    Thank you for code but in my case doesn't work. Converter return nothing. :(

  • DomKapDomKap USMember ✭✭

    Thank you.

  • amirvenusamirvenus USMember ✭✭✭

    @JorgeDiego said:
    Hi @DomKap

    The example I´ve sent you is working for me.
    Here you have a complete example https://drive.google.com/file/d/0B1MZ5Spc8EhvY2dWekpQVkFBSlE/view?usp=sharing

    There are a time picker and a button. The picker content is sync with the 'Hora' field in the ViewModel, and the reset button raise a command that reset the 'Hora' to the current time.

    If you have any issue, send me your code and I when I have a moment I´ll take a look.

    Good luck.

    Links is dead.

Sign In or Register to comment.