how do you change the time format in xamarin depending on the system setting?

At the end I found the answer from xamarin forms. You will need to change/add custom timepicker renderer.

This is the code

[assembly: ExportRenderer(typeof(TimePicker), typeof(TimeRenderer))]
namespace TabsApp.iOS.custom.renderers
{
    public class TimeRenderer : TimePickerRenderer
    {
       
        protected override void OnElementChanged(ElementChangedEventArgs<TimePicker> e)
        {
            base.OnElementChanged(e);

            if (Is12Hours())
            {
                Element.Format = "hh:mm tt";
            }
            else
            {
                var timePicker = (UIDatePicker)Control.InputView;  
                timePicker.Locale = new NSLocale("no_nb");

                Element.Format = "HH:mm";
            }
          
        }


        private bool Is12Hours()
        {
            var dateFormatter = new NSDateFormatter();
            dateFormatter.DateStyle = NSDateFormatterStyle.None;
            dateFormatter.TimeStyle = NSDateFormatterStyle.Short;

            var dateString = dateFormatter.ToString(NSDate.Now);
            var isTwelveHourFormat = 
                dateString.Contains(dateFormatter.AMSymbol) || 
                dateString.Contains(dateFormatter.PMSymbol);
            return isTwelveHourFormat;
        }
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top