Bir NSDateUTC'yi Objective C veya / ve Swift'te yerel saat dilimi NSDate'e nasıl dönüştürebilirim ?
Bir NSDateUTC'yi Objective C veya / ve Swift'te yerel saat dilimi NSDate'e nasıl dönüştürebilirim ?
Yanıtlar:
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"];
NSString* ts_utc_string = [df_utc stringFromDate:ts_utc];
NSString* ts_local_string = [df_local stringFromDate:ts_utc];
// you can also use NSDateFormatter dateFromString to go the opposite way
Dize parametrelerini biçimlendirme tablosu:
https://waracle.com/iphone-nsdateformatter-date-formatting-table/
Performans bir öncelikse, aşağıdakileri kullanmayı düşünebilirsiniz: strftime
NSDatenesneye dönüştürmenin gerekli olmadığı, ki bu doğru. Bir saat dilimine dönüştürme, tarih oluşturulurken değil, biçimlendirildiğinde gerçekleşir, çünkü tarihler saat dilimlerine sahip değildir.
NSCalendarDate.
EDIT Bunu yazdığımda muhtemelen daha iyi bir yaklaşım olan bir dateformatter kullanmalıyım bilmiyordum, bu yüzden slfcevabını da kontrol et .
UTC'de tarihleri döndüren bir web servisim var. Kullandığım toLocalTimeyerel saate dönüştürmek için ve toGlobalTimegerekirse geri dönüştürün.
Yanıtımı buradan aldım:
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
Bulduğum en kolay yöntem şudur:
NSDate *someDateInUTC = …;
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];
secondsFromGMTForDateYaz saatini hesaba katmak istiyorsanız , bir ek daha kullanılmalıdır. Bkz Elma Dokümanlar
Swift 3+ : UTC'den Yerel ve Yerel'den UTC'ye
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)
}
}
Yerel Tarih ve saat istiyorsanız. Bu kodu deneyin: -
NSString *localDate = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
[NSDate date]ile [NSDate dateWithNaturalLanguageString:sMyDateString].
UTC tarihinizi Yerel Tarih'e dönüştürün
-(NSString *)getLocalDateTimeFromUTC:(NSString *)strDate
{
NSDateFormatter *dtFormat = [[NSDateFormatter alloc] init];
[dtFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dtFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *aDate = [dtFormat dateFromString:strDate];
[dtFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[dtFormat setTimeZone:[NSTimeZone systemTimeZone]];
return [dtFormat stringFromDate:aDate];
}
Bunun gibi kullan
NSString *localDate = [self getLocalDateTimeFromUTC:@"yourUTCDate"];
Burada giriş currentUTCTime (08/30/2012 11:11 biçiminde) bir dizedir GMT'deki giriş süresini sistem ayarlı bölge saatine dönüştürür
//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 dateFromString: 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 string
NSString *localDate = [localDateFormatter stringFromDate: dateInUTC];
return localDate;
//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
NSString *time = [formatter stringFromDate:[NSDate date]]; // Current time
UTC takviminden tarihi uygun yerel NSTimeZone'a dönüştürün .
Bu yöntemi tarih saatini LocalTimeZone'umuza dönüştürmek için yazıyorum
-Burada (NSString *) TimeZone parametresi bir sunucu saat dilimidir
-(NSString *)convertTimeIntoLocal:(NSString *)defaultTime :(NSString *)TimeZone
{
NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init];
[serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:TimeZone]];
[serverFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *theDate = [serverFormatter dateFromString:defaultTime];
NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
[userFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[userFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateConverted = [userFormatter stringFromDate:theDate];
return dateConverted;
}
Kimse kullanmak gibi görünmediği için NSDateComponents, ben bir adım olacağını düşündüm ... Bu sürümde, hayır NSDateFormatterkullanılır, dolayısıyla dize ayrıştırma yok ve NSDateGMT (UTC) dışında zaman temsil etmek için kullanılmaz. Orijinal NSDatedeğişkendir 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_anotherCalendarolabilir NSCalendarIdentifierGregorianveya başka bir takvim olabilir. NSStringİzin i_anotherTimeZoneile elde edilebilir [NSTimeZone knownTimeZoneNames], ancak anotherCalendar.timeZoneolabilir [NSTimeZone defaultTimeZone]veya [NSTimeZone localTimeZone]veya[NSTimeZone systemTimeZone] tamamen.
Aslında anotherComponentsyeni zaman diliminde zamanı tutuyor. Fark edeceksiniz , çünkü GMT (UTC) anotherDatecinsinden i_datezamanı tutuyor.
Bunu deneyebilirsiniz:
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"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
NSMutableString *mu = [NSMutableString stringWithString:localDateString];
[mu insertString:@":" atIndex:3];
NSString *strTimeZone = [NSString stringWithFormat:@"(GMT%@)%@",mu,timeZone.name];
NSLog(@"%@",strTimeZone);
UTC saatini geçerli saat dilimine dönüştürün.
çağrı fonksiyonu
NSLocale *locale = [NSLocale autoupdatingCurrentLocale];
NSString *myLanguageCode = [locale objectForKey: NSLocaleLanguageCode];
NSString *myCountryCode = [locale objectForKey: NSLocaleCountryCode];
NSString *rfc3339DateTimeString = @"2015-02-15 00:00:00"];
NSDate *myDateTime = (NSDate*)[_myCommonFunctions _ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeString LanguageCode:myLanguageCode CountryCode:myCountryCode Formated:NO];
fonksiyon
-NSObject*)_ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeString LanguageCode:(NSString *)lgc CountryCode:(NSString *)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:[NSString stringWithFormat:@"%@", 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 string to an NSDate.
NSDate *date = [sRFC3339DateFormatter dateFromString:rfc3339DateTimeString];
if (formated == YES)
{
NSString *userVisibleDateTimeString;
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 string.
userVisibleDateTimeString = [sUserVisibleDateFormatter stringFromDate:date];
return (NSObject*)userVisibleDateTimeString;
}
}
return (NSObject*)date;
}