objective objective-c ios datetime nsdate nsdateformatter

objective-c - objective - string to date swift 4



NSDateFormatter en modo de 12 horas (4)

tengo el siguiente código.

NSDateFormatter *df = ...; [df setTimeZone:[NSTimeZone defaultTimeZone]]; [df setDateFormat:@"yyyy-MM-dd''T''HH:mm:ss.SSSZZZ"]; NSDate * date = [df dateFromString:date_string]; //here is the problem

En el modo de 24 horas todo está bien. Cuando se configura el modo de 12 horas en el dispositivo, stringFromDate devuelve null. El formato de date_string es el mismo todo el tiempo, el formato de fecha también. ¿Por que sucede?


En su NSDateFormatter "yyyy-MM-dd''T''HH:mm:ss.SSSZZZ" HH significa 24 horas y hh significa 12 horas


Modo de 12 horas a modo de 24 horas:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"hh:mm a"]; NSDate *amPmDate = [formatter dateFromString:amPmHourString]; [formatter setDateFormat:@"HH:mm"]; NSString *24HourString = [formatter stringFromDate:amPmDate]];

Para el modo de 24 horas a 12 horas, haga lo contrario.


Trate de establecer la configuración regional de esta manera:

NSLocale *twelveHourLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; df.locale = twelveHourLocale;

Para forzar en lugar de 24 horas, puedes usar:

NSLocale *twentyFour = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];


NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; [dateFormat setLocale:locale];