Wrong date in UIDatePicker Xamarin iOS

I want to set Minimum Date(Jan 01 1996) and Maximum date(Now) in UIDatePicker to select Date of Birth. However when I set Maximum and minimum date then it gives me wrong date. Actually date with -1 day.
Screenshot 1 screenshot 2

CODE:

public static NSDate GetChildMaxNSDate ()
{
        return NSDate.Now;
}

public static NSDate GetChildMinNSDate ()
{
    NSDateFormatter dateFormatter = new NSDateFormatter ();
    dateFormatter.TimeZone = NSTimeZone.LocalTimeZone;
    dateFormatter.DateFormat = ChildDOBFormat;

    return dateFormatter.Parse (ChildStartDate);
}

void SetChildDatePicker ()
{
    // Set DatePicker view enabled when user clicks on date of birth textfield.
    UIDatePicker childDOBPicker = new UIDatePicker ();
    childDOBPicker.Mode = UIDatePickerMode.Date;

    childDOBPicker.MinimumDate = StringUtil.GetChildMinNSDate ();
    childDOBPicker.MaximumDate = StringUtil.GetChildMaxNSDate ();
    childDOBPicker.SetDate (NSDate.Now, false);
    childDOBPicker.TimeZone = NSTimeZone.LocalTimeZone;
    childDOBPicker.Calendar = NSCalendar.CurrentCalendar;

    childDOBPicker.ValueChanged -= ChildDOBSelected;
    childDOBPicker.ValueChanged += ChildDOBSelected;

    // Set toolbar to dismiss DatePicker.
    var dobToolBar = new UIToolbar (new CGRect (0, 0, 320, 50));
    dobToolBar.BarStyle = UIBarStyle.Default;
    dobToolBar.Items = new UIBarButtonItem[] {
        new UIBarButtonItem (UIBarButtonSystemItem.FlexibleSpace),
        new UIBarButtonItem (UIBarButtonSystemItem.Done, (sender, args) => {
            TxtChdDOB.ResignFirstResponder ();
        })
    };
    dobToolBar.SizeToFit ();

    TxtChdDOB.InputView = childDOBPicker;
    TxtChdDOB.InputAccessoryView = dobToolBar;
}

Answers

  • HofmaDresuHofmaDresu USUniversity

    Did you find the solution to this? I'm also seeing the same problem with MaximumDate on UIDatePicker

  • YogeshPatil.2761YogeshPatil.2761 USMember ✭✭

    @MattHoffman.8791, sadly no. But I did one trick when user selects date out of range then picker date is changed back to reference date.
    This may be helpful for you

    void ChildDOBSelected(object sender, EventArgs e)
    {
        var dobDatePicker = sender as UIDatePicker;
        DateTime dob = StringDateUtil.GetDateTimeFromNSDate(dobDatePicker.Date);
        if (StringDateUtil.IsFutureDate(dob) || StringDateUtil.IsChildAgeTooLarge(dob))
        {
            var date = StringDateUtil.GetNSDateFromDateTime(DateTime.Today.AddYears(-1));
            dobDatePicker.SetDate(date, true);
            return;
        }
    
        // Use selected date.
    }
    
Sign In or Register to comment.