Add AM/PM to datepicker?
Asked Answered
A

4

6

My UIDatePicker is set to UIDatePickerModeTime but on the apple documentation it says The date picker displays hours, minutes, and (optionally) an AM/PM designation. The exact items shown and their order depend upon the locale set. An example of this mode is [ 6 | 53 | PM ].. How do i add AM/PM because on my device, those aren't options and it instead uses a 24 hour clock?

Algebraist answered 27/1, 2011 at 22:33 Comment(0)
E
22

This will depend on the settings of the user. If you go to Settings -> General -> Date & Time. there is a "24-Hour" time switch, and based on that users will have the AM/PM indicator on your picker.

Encomiastic answered 27/1, 2011 at 22:36 Comment(1)
This is true, but it can easily be overruled by setting the locale if needed for some reasons.Polyhedron
S
3

Unfortunately UIDatePicker doesn't have an option for that; it always respects the device option of 12-hour or 24-hour time.

If you must have an AM/PM component you may have to go with a custom UIPickerView instead, and build an NSDate out of its components manually.

Scherle answered 27/1, 2011 at 22:36 Comment(1)
try datepicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];Woodpecker
P
2

This thread is somewhat old, but maybe this will be useful to someone else...

As written in the original question, the picker will respect the locale. So, if you what to overrule the system-settings you can set the desired locale on the picker like this:

picker.locale = Locale.init(identifier: "en")
Polyhedron answered 20/10, 2021 at 13:34 Comment(0)
L
1

Two things to check,

  • UIDatePicker has mode which needs to be either set to .time or .dateAndTime in order to support AM/PM format.
  • set locale to a locale that supports AM/PM, eg "en_US_POSIX", if your locale is set to current, it will read system locale.
Leftward answered 3/10, 2022 at 8:30 Comment(2)
Changing datePickerMode has nothing to do with it. It's sufficient to set desired locale.Coffeepot
@Coffeepot if its just .date, you won't see AM/PM even if the locale is set properlyLeftward

© 2022 - 2024 — McMap. All rights reserved.