假设我在服务器@“2014-03-08T16:59 + 0000”中有这样的字符串。
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [self dateFromJSONString:@"2014-03-08T16:59+0000"];
NSDateComponents *dateComponents = [calendar components:(NSTimeZoneCalendarUnit) fromDate:date];
NSLog(@"TimeZone is %@", [[dateComponents timeZone] abbreviation]);
但TimeZone并非基于字符串,而是基于设备的currentTimeZone。
是否可以从字符串中提取timeZone?
答案 0 :(得分:2)
您必须自己从字符串中解析GMT的偏移量。
这样的事情,但你必须调整你的略有不同的格式:
/**
This is assuming format yyyy-MM-dd'T'HH:mm:ssZZZZZ . ie the last 5 chars are timezone offset from gtm in the form (+|-)##:##
*/
-(NSTimeZone*)timezoneFromDateString:(NSString*)dateString {
NSTimeZone *timezone = nil;
NSString *timezoneComponent = [dateString substringFromIndex:19];
if(timezoneComponent.length == 6) {
NSArray *components = [[timezoneComponent substringFromIndex:1] componentsSeparatedByString:@":"];
NSInteger offset = [[timezoneComponent substringToIndex:1] isEqualToString:@"-"] ? -1 : 1;
if(components.count == 2) {
offset *= [components[0] integerValue] * 60*60 + [components[1] integerValue] *60;
timezone = [NSTimeZone timeZoneForSecondsFromGMT:offset];
}
}
return timezone;
}
答案 1 :(得分:1)
如果您确定需要解析的字符串始终以这种方式格式化,那么正则表达式提供了一种简单的方法:
NSString *str = @"2014-03-08T16:59+0000";
NSString *pattern = @"^.*T\\d{2}:\\d{2}";
NSString *timezone = [str stringByReplacingOccurrencesOfString: pattern
withString: @""
options: NSRegularExpressionSearch
range: NSMakeRange(0, str.length)];
答案 2 :(得分:1)
-(NSArray*)convertToLocalDate:(NSString*)dateStr{
NSArray *convert;
NSString *time=@"";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *date = [dateFormatter1 dateFromString:dateStr];
//NSLog(@"date : %@",date);
NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
NSDate *destinationDate = [[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date] ;
NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
[dateFormatters setDateFormat:@"dd.MM.yyyy"];
[dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];
dateStr = [dateFormatters stringFromDate: destinationDate];
NSDateFormatter *dateFormatters1 = [[NSDateFormatter alloc] init];
[dateFormatters1 setDateFormat:@"hh:mm a"];
[dateFormatters1 setTimeZone:[NSTimeZone systemTimeZone]];
time = [dateFormatters1 stringFromDate: destinationDate];
convert = [[NSArray alloc ]initWithObjects:dateStr,time,nil];
return convert;
}