Reputation: 895
I can't convert my NSString to NSDate. here's the code:
+ (NSDate *) stringToNSDate: (NSString *) dateString{
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
NSLog(@"dateString: %@ datefromstring: %@", dateString, dateFromString);
return dateFromString;
}
//dateFromString is nil.
What should I do? Thanks!
btw, dateString will always contain a string-ed date in this format: "2012/02/10 08:01:25 +0000"
Upvotes: 0
Views: 348
Reputation: 95405
From the information you've given, the problem appears to be that your dateString
separates the date components with slashes (\
), but your date formatter is expecting dashes (-
).
To answer your other question, you can use stringByReplacingOccurrencesOfString:withString:
.
For example:
NSString *date1 = @"2012/12/10 ...";
NSString *date2 = [date1 stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
Note that this will replace every /
with -
, so just be careful about timezones etc.
Upvotes: 3
Reputation: 3312
Try this instead:
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss ZZZ"];
Upvotes: 2