Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter with 24 hour times

I have a countdown timer which countsdown from the current date/time to a specific future date/time. It is working great except for one problem. I input the future date using NSDateFormatter and dateFromString. It doesn't seem to be able to accept any time (hour) over 12 though indicating it is not support 24 hour clock. Is there a way to enable 24 hour clock support or a workaround? Here is some of my code:

NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; NSDate *myDate = [df dateFromString:@"2010-03-14 15:00:00"]; 
like image 806
John Avatar asked Jan 25 '10 20:01

John


People also ask

How do you convert 12 hours to 24 hours in Swift?

import Foundation let afternoonHour = try Date("2021-10-23T02:37:12Z", strategy: . iso8601) // this format to 24 hour let dateFormatter = DateFormatter() dateFormatter. dateFormat = "HH:mm:ss" let twentyFourHour = dateFormatter. string(from: afternoonHour) print(twentyFourHour) // with the new Date.

What is en_US_POSIX?

In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences.


2 Answers

NSDateFormatter follows the Unicode standard for date and time patterns. Use 'H' for the hour on a 24-hour clock:

NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *myDate = [df dateFromString:@"2010-03-14 15:00:00"]; 
like image 112
VoidPointer Avatar answered Sep 28 '22 10:09

VoidPointer


I had the same problem and using HH worked only on some devices, like Roger also verified. In the end this was the solution that worked for me, I hope it works for others. Finding this answer was difficult, there are no forums with it, it was literally trial and error following the apple documentation.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];     NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];      [dateFormatter setLocale:enUSPOSIXLocale];      NSString *dateFormat = @"dd/MM/yyyy HH:mm"; //MM for month, mm for minutes      [dateFormatter setDateFormat:dateFormat];     [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];     date = [dateFormatter dateFromString:string]; 
like image 22
crojassoto Avatar answered Sep 28 '22 12:09

crojassoto