My problem is there is a switch in my app which toggles for 12 hour and 24 hour time format.I am displaying my labels time according to that, but the UIDatePicker
Easily format the result instead
Since the device local are not in 24 hour. select time in 12h format has no problem. mainly this issue occurs when you are trying to submit a time to server. and the server requesting it on 24 hour format.
However, for user it is easier for user to used 12h format rather 24h format. but server are usually required time to be in 24h format.
Since you mention
not on device Settings
I can only assume you are trying to make this happen without interrupt user default setting on the Phone. But if your issue is with the view, then
myDatePicker.locale = NSLocale(localeIdentifier: "en_GB")
is the only way to do it.
What I did was not display it in 24h format but convert the result value to 24h format.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
print("\(pickerView.date)") // 10:30 PM
let dateSelect = dateFormatter.string(from: pickerView.date)//pickerView = to your UIDatePicker()
self.tfclosing.text = dateSelect // 22:30
Try this code to show 24 Hrs Format in DatePicker
:
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"NL"];
[self.datePicker setLocale:locale];
If I understand you correctly you need to find out whether the device settings is has 12 hrs or 24 hrs format. Sorry if this solution is a little late.
-(BOOL)returnDefaultDateFormat
{
NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
NSRange containsA = [formatStringForHours rangeOfString:@"a"];
BOOL hasAMPM = containsA.location != NSNotFound;
return hasAMPM;
}
There is no need of any single Line of Code. We can set the locale from Story Board also, I have attached the screenshot.
And to do this programmatically we can also write the following code.
dateTimePicker.locale = Locale(identifier: "en_GB")