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"];
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.
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.
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"];
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With