Ale
Ale

Reputation: 2344

iOS time in 24 hours format

I want to get the current time and parse it to an String in 24 hours format, for example 13:30.

This is my code:

NSDate *date = [NSDate date];
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"HH:mm"];
NSString *timeString = [formatter stringFromDate:date];

It works on the iOS simulator, but on my iPad I get 3:30 PM.

I have played around with different formats but still the same result.

Any idea why?

Thanks in advance.

Upvotes: 4

Views: 1522

Answers (2)

neuhaus
neuhaus

Reputation: 4094

You need to explicitly set the locale to one with a 24 hour time.

See NSDateFormatter Locale for details on how to set the locale for the NSDateFormatter.

Note the answer by @mtb to that question. It explains how to not use a locale.

Upvotes: 1

zaph
zaph

Reputation: 112857

The issue is the user's local is set to a 12 hour format. Set the local to en_US_POSIX to over-ride the user's setting.

dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

Upvotes: 2

Related Questions