[英]Problems of time zones “ZE8”, How to convert NSDate to NSString
怎么轉換(ZE12 / 27/2013 05:49:41 PM) 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獲取空值。 那是什么問題?
出現問題是因為ZE8
格式對於unix系統中的時區不是有效格式!
您可以使用:
但是ZE8無效
您必須將此數據轉換為有效的數據,因此您必須添加另一個Array / table / dictionary,並使用此值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:
方法,其余的將放在一個地方。
希望這會幫助你。
嘗試
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
[formatter release];
祝一切順利
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.