如何转换(2013年12月27日05:49:41 ZE8) NSString转换为NSDate?
NSString *string = @"12/27/2013 05:49:41 PM ZE8";
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a z"];
NSDate *publishDate = [formatter dateFromString:string];
publishDate获取空值。问题是什么?
答案 0 :(得分:5)
问题出现是因为ZE8
格式是非有效的unix系统时区格式!
您可以使用:
但是ZE8无效
您必须将此数据转换为有效数据,因此您必须使用此值http://www.ibm.com/developerworks/lotus/library/ls-keeping_time/side1.html添加另一个数组/表格/字典,并将其转换为RFC 822
,例如
不,没有内置方式 - 你必须自己编写这个结构。例如使用字典(如果我是你,我将自己写一个类别)。我为你写了一个简单的解决方案,当然如果你经常这样做,你应该把这个字典保存在某个地方,并写上面页面的所有值(我只写两个):
-(void)myBaseMethod {
NSDate *finalDate = [self convertStringToDate:@"12/27/2013 05:49:41 PM ZE8"];
}
-(NSDate*)convertStringToDate:(NSString*)str {
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a z"];
return [formatter dateFromString:[self changeTimeZoneToValidOneFromString:str]];
}
-(NSString*)changeTimeZoneToValidOneFromString:(NSString*)inputStrDate {
NSDictionary *timeZonesDic = [NSDictionary dictionaryWithObjectsAndKeys:
@"GMT-08:00",@"ZE8",
@"GMT-7:00",@"ZE7",
nil];
NSMutableArray *dateItems = [[inputStrDate componentsSeparatedByString:@" "] mutableCopy]; //in here I break the original string into array of strings (every element is separate date component)
NSString *timeZoneString = [timeZonesDic objectForKey:[dateItems lastObject]]; //convert using dictionary
[dateItems replaceObjectAtIndex:([dateItems count]-1) withObject:timeZoneString]; //replacing the last object of the existing array.
return [dateItems componentsJoinedByString:@" "]; //in here I join it back together
}
真的为Category
(NSDate
)制作,然后您将只调用convertStringToDate:
方法,其余的将在一个地方。
希望这会对你有所帮助。
答案 1 :(得分:-2)
尝试
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
[formatter release];
一切顺利