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"
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.
Try this instead:
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss ZZZ"];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.