Drunken Daddy
Drunken Daddy

Reputation: 7991

Xamarin.iOS UITextField date format not working

I've a UITextField which when clicked opens a DatePicker. I want time to be shown in the TextField in hh:mm tt (like 2:10 PM)

void InitTimePicker()
{
    timePicker = new ModalPickerViewController(ModalPickerType.Date, "Select A Time", this)
    {
        HeaderBackgroundColor = UIColor.Red,
        HeaderTextColor = UIColor.White,
        TransitioningDelegate = new ModalPickerTransitionDelegate(),
        ModalPresentationStyle = UIModalPresentationStyle.Custom
    };
    timePicker.DatePicker.Mode = UIDatePickerMode.Time;
    timePicker.OnModalPickerDismissed += (sim, ea) =>
    {
        var timeFormatter = new NSDateFormatter()
        {
            DateFormat = "hh:mm tt"
        };
        vitalEntryTimeTextField.Text = timeFormatter.ToString(timePicker.DatePicker.Date);
    };
    vitalEntryTimeTextField.ShouldBeginEditing = (textView) =>
    {
        textView.ResignFirstResponder();
        PresentViewControllerAsync(timePicker, true);
        return true;
    };
}

the DatePicker shows and everything works. but when I select the time in the datepicker and click done, the time shown in the TextField is like 2:10. AM/PM is not showing though I specified

DateFormat = "hh:mm tt"

What am I doing wrong here?

Upvotes: 0

Views: 731

Answers (1)

BytesGuy
BytesGuy

Reputation: 4127

Here you are using a NSDateFormatter which is from the iOS SDK but specifying the DateFormat using the C# specifiers

AM/PM will not be shown when the iOS device has 24 hour format turned on:

Settings -> General -> Date & Time -> 24 Hour

Obviously you cannot guarantee 24 hour time will not be enabled on every device.

You can specify the locale for the time format. Specifically, en_US uses 12 hour time by default.

NSLocale myLocale = new NSLocale("en_US");
var timeFormatter = new NSDateFormatter()
{
    Locale = myLocale,
    DateFormat = "hh:mm a"
};

This would give you something like 01:15 PM.

Use HH:mm a to give you something like 13:15 PM.

Upvotes: 1

Related Questions