iOS: Convertir le NSDate UTC en fuseau horaire local

Comment convertir un NSDate UTC en un fuseau horaire local NSDate en Objective C ou / et Swift?

 NSTimeInterval seconds; // assume this exists NSDate* ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds]; NSDateFormatter* df_utc = [[[NSDateFormatter alloc] init] autorelease]; [df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; [df_utc setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"]; NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease]; [df_local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]]; [df_local setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"]; NSSsortingng* ts_utc_ssortingng = [df_utc ssortingngFromDate:ts_utc]; NSSsortingng* ts_local_ssortingng = [df_local ssortingngFromDate:ts_utc]; // you can also use NSDateFormatter dateFromSsortingng to go the opposite way 

Tableau des parameters de chaîne de formatage:

https://waracle.com/iphone-nsdateformatter-date-formatting-table/.

Si la performance est une priorité, vous pouvez envisager d’utiliser strftime

https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/strftime.3.html

EDIT Quand j’ai écrit ceci, je ne savais pas que je devrais utiliser un format de date, ce qui est probablement une meilleure approche, alors slf aussi la réponse de slf .

J’ai un webservice qui renvoie des dates en UTC. J’utilise toLocalTime pour le convertir en heure locale et toGlobalTime pour le reconvertir si nécessaire.

C’est là que j’ai reçu ma réponse:

https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/

 @implementation NSDate(Utils) -(NSDate *) toLocalTime { NSTimeZone *tz = [NSTimeZone defaultTimeZone]; NSInteger seconds = [tz secondsFromGMTForDate: self]; return [NSDate dateWithTimeInterval: seconds sinceDate: self]; } -(NSDate *) toGlobalTime { NSTimeZone *tz = [NSTimeZone defaultTimeZone]; NSInteger seconds = -[tz secondsFromGMTForDate: self]; return [NSDate dateWithTimeInterval: seconds sinceDate: self]; } @end 

La méthode la plus simple que j’ai trouvée est la suivante:

 NSDate *someDateInUTC = …; NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT]; NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds]; 

Si vous voulez la date et l’heure locales. Essayez ce code: –

 NSSsortingng *localDate = [NSDateFormatter localizedSsortingngFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle]; 

Swift 3+ : UTC vers local et local vers UTC

 extension Date { // Convert UTC (or GMT) to local time func toLocalTime() -> Date { let timezone = TimeZone.current let seconds = TimeInterval(timezone.secondsFromGMT(for: self)) return Date(timeInterval: seconds, since: self) } // Convert local time to UTC (or GMT) func toGlobalTime() -> Date { let timezone = TimeZone.current let seconds = -TimeInterval(timezone.secondsFromGMT(for: self)) return Date(timeInterval: seconds, since: self) } } 

Ici, l’entrée est une chaîne currentUTCTime (au format 30/08/2012 11:11) convertit le temps d’entrée en heure GMT en heure de la zone définie par le système

 //UTC time NSDateFormatter *utcDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [utcDateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"]; [utcDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: 0]]; // utc format NSDate *dateInUTC = [utcDateFormatter dateFromSsortingng: currentUTCTime]; // offset second NSInteger seconds = [[NSTimeZone systemTimeZone] secondsFromGMT]; // format it and send NSDateFormatter *localDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [localDateFormatter setDateFormat:@"MM/dd/yyyy HH:mm"]; [localDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: seconds]]; // formatted ssortingng NSSsortingng *localDate = [localDateFormatter ssortingngFromDate: dateInUTC]; return localDate; 

Convertissez votre date UTC en date locale

 -(NSSsortingng *)getLocalDateTimeFromUTC:(NSSsortingng *)strDate { NSDateFormatter *dtFormat = [[NSDateFormatter alloc] init]; [dtFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; [dtFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; NSDate *aDate = [dtFormat dateFromSsortingng:strDate]; [dtFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; [dtFormat setTimeZone:[NSTimeZone systemTimeZone]]; return [dtFormat ssortingngFromDate:aDate]; } 

Utiliser comme ça

 NSSsortingng *localDate = [self getLocalDateTimeFromUTC:@"yourUTCDate"]; 

Convertissez la date du calendrier UTC en un seul avec le NSTimeZone local approprié .

 //This is basic way to get time of any GMT time. NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"hh:mm a"]; // 09:30 AM [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:1]]; // For GMT+1 NSSsortingng *time = [formatter ssortingngFromDate:[NSDate date]]; // Current time 

J’écris cette méthode pour convertir l’heure de la date à notre LocalTimeZone

-Here (NSSsortingng *) Le paramètre TimeZone est un fuseau horaire du serveur

 -(NSSsortingng *)convertTimeIntoLocal:(NSSsortingng *)defaultTime :(NSSsortingng *)TimeZone { NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init]; [serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:TimeZone]]; [serverFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *theDate = [serverFormatter dateFromSsortingng:defaultTime]; NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init]; [userFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; [userFormatter setTimeZone:[NSTimeZone localTimeZone]]; NSSsortingng *dateConverted = [userFormatter ssortingngFromDate:theDate]; return dateConverted; } 

Comme personne ne semblait utiliser NSDateComponents , je pensais en utiliser un dans … Dans cette version, aucun NSDateFormatter n’est utilisé, donc pas d’parsing de chaîne, et NSDate n’est pas utilisé pour représenter l’heure en dehors de GMT (UTC). Le NSDate original est dans la variable i_date .

 NSCalendar *anotherCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:i_anotherCalendar]; anotherCalendar.timeZone = [NSTimeZone timeZoneWithName:i_anotherTimeZone]; NSDateComponents *anotherComponents = [anotherCalendar components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitNanosecond) fromDate:i_date]; // The following is just for checking anotherComponents.calendar = anotherCalendar; // anotherComponents.date is nil without this NSDate *anotherDate = anotherComponents.date; 

i_anotherCalendar peut être NSCalendarIdentifierGregorian ou tout autre calendrier. Le NSSsortingng autorisé pour i_anotherTimeZone peut être acquis avec [NSTimeZone knownTimeZoneNames] , mais anotherCalendar.timeZone peut être [NSTimeZone defaultTimeZone] ou [NSTimeZone localTimeZone] ou [NSTimeZone systemTimeZone] .

Il s’agit en fait d’un autre anotherComponents contenant l’heure dans le nouveau fuseau horaire. Vous remarquerez que anotherDate est égal à i_date , car il conserve l’heure GMT (UTC).

Convertissez l’heure UTC en fuseau horaire actuel.

fonction d’appel

 NSLocale *locale = [NSLocale autoupdatingCurrentLocale]; NSSsortingng *myLanguageCode = [locale objectForKey: NSLocaleLanguageCode]; NSSsortingng *myCountryCode = [locale objectForKey: NSLocaleCountryCode]; NSSsortingng *rfc3339DateTimeSsortingng = @"2015-02-15 00:00:00"]; NSDate *myDateTime = (NSDate*)[_myCommonFunctions _ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeSsortingng LanguageCode:myLanguageCode CountryCode:myCountryCode Formated:NO]; 

Fonction

 -NSObject*)_ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeSsortingng LanguageCode:(NSSsortingng *)lgc CountryCode:(NSSsortingng *)ctc Formated:(BOOL) formated { NSDateFormatter *sUserVisibleDateFormatter = nil; NSDateFormatter *sRFC3339DateFormatter = nil; NSTimeZone *timeZone = [NSTimeZone defaultTimeZone]; if (sRFC3339DateFormatter == nil) { sRFC3339DateFormatter = [[NSDateFormatter alloc] init]; NSLocale *myPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:[NSSsortingng ssortingngWithFormat:@"%@", timeZone]]; [sRFC3339DateFormatter setLocale:myPOSIXLocale]; [sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"]; [sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; } // Convert the RFC 3339 date time ssortingng to an NSDate. NSDate *date = [sRFC3339DateFormatter dateFromSsortingng:rfc3339DateTimeSsortingng]; if (formated == YES) { NSSsortingng *userVisibleDateTimeSsortingng; if (date != nil) { if (sUserVisibleDateFormatter == nil) { sUserVisibleDateFormatter = [[NSDateFormatter alloc] init]; [sUserVisibleDateFormatter setDateStyle:NSDateFormatterMediumStyle]; [sUserVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle]; } // Convert the date object to a user-visible date ssortingng. userVisibleDateTimeSsortingng = [sUserVisibleDateFormatter ssortingngFromDate:date]; return (NSObject*)userVisibleDateTimeSsortingng; } } return (NSObject*)date; } 

Vous pouvez essayer celui-ci:

 NSDate *currentDate = [[NSDate alloc] init]; NSTimeZone *timeZone = [NSTimeZone defaultTimeZone]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterLongStyle]; [dateFormatter setTimeStyle:NSDateFormatterLongStyle]; [dateFormatter setTimeZone:timeZone]; [dateFormatter setDateFormat:@"ZZZ"]; NSSsortingng *localDateSsortingng = [dateFormatter ssortingngFromDate:currentDate]; NSMutableSsortingng *mu = [NSMutableSsortingng ssortingngWithSsortingng:localDateSsortingng]; [mu insertSsortingng:@":" atIndex:3]; NSSsortingng *strTimeZone = [NSSsortingng ssortingngWithFormat:@"(GMT%@)%@",mu,timeZone.name]; NSLog(@"%@",strTimeZone);