Forum Xamarin.Forms

TimeSpan to String

I have a page where I am attempting to save the time of a time picker to a string and I keep getting 00:00:00.
I am sending it to my EventItem page through binding from my EventList page.
So I have foo_time.SetBinding(TimePicker.TimeProperty, "EventStartTime"); for start time and similar for end time.
Then I take the foo_string.Text = stime.Time.ToString(); to pull the time into a string.

Ideally I would love to have it display something like 5:00 AM, but below are some of the things I have tried with no luck:
foo_string = new DateTime(foo_time.Time.Ticks).ToString("h:mm tt")
foo_string = foo_time.Time.ToString(@"h:mm");

Side note, I am basically creating temporary timepicker just to bind the time to it so I can pull the time from it and the timepicker is never used. I am doing the same for datepicker and labels, so if there is an easier way to call a binding than something like below I would LOVE to know as my code looks bloated:
temp_lbl.SetBinding(Label.TextProperty, "EventAddress");
addr = temp_lbl.Text;

Best Answers

Answers

  • clintonboozeclintonbooze USMember ✭✭
    edited September 2016

    also tried int h = temp_tp.Time.Hours; with no luck, just returned a zero. =(

  • clintonboozeclintonbooze USMember ✭✭
    edited September 2016

    @JohnHardman
    First off thank you so much for the quick response and such detail. =)
    And sorry but I'm about to noob it up here, sorry. =(

    I simply want to display it, basically I have 2 time start and end saved as TimeSpans that I want to display as something like 5:00 AM - 6:00 PM, but no editing happening so it is just a one way binding, and as you said, I am unsure if I even need a binding. Binding is the only way I know of to extract the data that is passed into the page. If there is another way by all means point me in the correct direction, but as I said I am a bit of a learning (noob) developer and learning as I go. =P
    Yes, I do have a class, here is a basic piece, I removed a bunch to make it more condensed:

    public class AdEvent {
            public int EventID { get; set; }
            public string EventGUID { get; set; }        
            public string EventName { get; set; }
            public DateTime EventDate { get; set; }
            public TimeSpan EventStartTime { get; set; } //the start time
            public TimeSpan EventEndTime { get; set; } //the end time
        }
    

    Now you said "bind a View to a property", Are you referring to what I am currently doing by passing in an object to the view then using binding to extract data and save it to labels and what not?

    I did make comments on your code to ensure I understand it and put ? where I am not exactly sure what it is doing or asking for.
    I am not sure about how to go about implementing this, how do I extract the data to even send it to this converter?

    public class TimeSpanToTimeStringConverter : IValueConverter
    {
        public static TimeSpanToTimeStringConverter Instance = new TimeSpanToTimeStringConverter();
    
        public object Convert(object value, //the TimeSpan variable? if so im unsure how to get
                                            //that info without binding to picker then pulling from picker
                                            //that always ends up being zero once extracted from picker
                              Type targetType, //String?
                              object parameter, //??
                              System.Globalization.CultureInfo culture) //passing in the language? like en-US?
        {
            TimeSpan timeSpan = (TimeSpan)value; //saves the 'value' of the timespan?
            DateTime dateTime = DateTime.MinValue + timeSpan; //zeroing out the DateTime then adding the TimeSpan
    
            DateTimeFormatInfo dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat; //setting the format for the datetime to culture 'en-US' for example
            string shortTimePattern
                = dateTimeFormat.LongTimePattern.Replace(":ss", String.Empty).Replace(":s", String.Empty);
                //will save it as a 'h:mm:ss tt' then remove the ':ss' and ':s' leaving it as 'h:mm tt'
    
            return dateTime.ToString(shortTimePattern); //returning the result of 'h:mm tt'
        }
    
        //not really sure, seems to be for exception, but i am unsure how it gets called or what exactly it does
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException("TimeSpanToTimeStringConverter.ConvertBack");
        }
    }
    

    Just want to say thank you for your help on this ahead of time. =D

  • clintonboozeclintonbooze USMember ✭✭

    @JohnHardman Thank you so much, no need for any apologies, you are helping me out. :wink:
    I will give this a shot now. :smiley:

  • clintonboozeclintonbooze USMember ✭✭

    @JohnHardman Hmmmm, still nada, I have been doing some debugging, again...lol
    It seems like there is more of an issue that I think is the reason I keep getting zeros and nulls but am unsure exactly why is causing the issue. So I have a EventList page that that lists the events. Then I have a method that runs when one is selected:

    void OnItemSelected(object sender, SelectedItemChangedEventArgs e) {
                var event_item = e.SelectedItem as AdEvent;
                var event_page = new EventItem();
                event_page.BindingContext = event_item;
                Navigation.PushAsync(event_page);
            }
    

    Which sends the AdEvent object to the EventItem page to display the information. Now I have line by line debugged the event_item in the OnItemSelected method and it is containing the proper information pulled from the server. But on the bindings most of the data is binding null, and I am lost as to why.

    Here is what I have done and issues I am running into.
    Now, doesn't var the_event = (AdEvent)BindingContext; run on the EventItem page save the bound item of event_item which is an AdEvent object to the the_event variable? If so then I have an issue as the the_event is showing as null while debugging the EventItem page.

    Also, going line by line the only thing that is getting saved/bound is the date, how and why only that one I have no idea, but everything else is null and I am flabbergast as to why.

  • JohnHardmanJohnHardman GBUniversity mod

    @clintonbooze - the code snippet there looks ok to me. Unfortunately, debugging bindings is a painful process (I've spent much of today doing it on some of my own code).

    It probably won't help with this immediate problem, but when debugging bindings it can be useful to throw in a dummy ValueConverter, as it provides places to put breakpoints and to check values are as expected. The DummyConverter is:

    public class DummyConverter : IValueConverter
    {
        public static DummyConverter Instance = new DummyConverter();
    
        private DummyConverter()
        {
            // no-op
        }
    
        public object Convert(object value, Type targetType,
                                object parameter, CultureInfo culture)
        {
            return value;
        }
    
        public object ConvertBack(object value, Type targetType,
                                    object parameter, CultureInfo culture)
        {
            return value;
        }
    
    } // public class DummyConverter : IValueConverter
    

    As to the problem you are hitting now, it would take a chunk more code to be able to identify a cause. Typical causes of problems around bindings include PropertyChanged not being raised or not being monitored, typos in names meaning things don't match up (e.g. in the code above I used "StartingTimeSpan" - I never do that in practice, as if there's a single character wrong, things won't work. I typically use nameof(...) instead). BindingMode being wrong, there are probably others.

    If you cannot find the problem, I suggest starting a new thread, as the problem is not related to binding a TimeSpan any more.

  • clintonboozeclintonbooze USMember ✭✭
    edited September 2016

    @JohnHardman
    Ok. Figured it all out, thank you for being so patient with me. There were several issues going on here.

    1. My coworker who I have been telling this issue about this whole time has now decided to tell me that the time variables from the server portal are being sent as strings even though the class is TimeSpan. So somehow it was showing in the AdEvent on the EventList alright but when I bound it there were issues. IDK, whatever that's 1 down.

    2. With the var the_event = (AdEvent)BindingContex; storing null was do to the fact that EventItem() page being called has a method in it I made called set_elements() that is called on creation that does all the bindings, text assignments and formatting. This is what had the var the_event = (AdEvent)BindingContex; in it which since the binding had not happened yet resulted in a null. So on the EventList calling the method before sending fixed it. Now its not perfect but it works.

    void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
            {
                var event_item = e.SelectedItem as AdEvent;
                var event_page = new EventItem();
                event_page.BindingContext = event_item;
                event_page.set_elements();
                Navigation.PushAsync(event_page);
            }
    

    Thank again man. =)

Sign In or Register to comment.