Reputation: 631
How to convert (12/27/2013 05:49:41 PM ZE8) NSString to 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 is getting null value. What is issue that?
Upvotes: 2
Views: 1458
Reputation: 13860
The problem appears because ZE8
format is NOT valid format for timezones in unix systems!
You can use:
But ZE8 is invalid
You have to convert this data to valid one, so you have to add another Array/table/dictionary what do you like with this values http://www.ibm.com/developerworks/lotus/library/ls-keeping_time/side1.html and convert it to RFC 822
for example
No, there is no built in way - you have to write this structure by yourself. For example using dictionary (if i were you i will write a category by myself). I write a simple solution for you, of course if you do this often you should keep this dictionary somewhere and also write all the values from above page (i write only two):
-(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
}
Really make a Category
(NSDate
) for it, then you will be call only convertStringToDate:
method and the rest will be in one place.
Hope this will help you.
Upvotes: 5
Reputation: 39384
Try
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];
//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];
NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
[formatter release];
All the best
Upvotes: -2