How to parse a date string with Objective-C
How can i parse an NSString who who have this form "2011052620110529" to get each value as a NSString ? i tried to write this
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"yyyyMMdd开发者_JS百科yyyyMMdd"];
but i don't think it's correct ... Help me please
(I'm assuming here you mean "parse it into dates", not "parse it into two strings." Your question is not clear.)
That string doesn't represent a single valid moment in time; rather, it represents (presumably) a range of time.
You'll have to split the string in two before parsing the two dates, then get the interval between them. Assuming each component is always 8 characters long:
NSString *strComplete = ...;
NSString *strFirstDate = [strComplete substringToIndex: 8];
NSString *strSecondDate = [strComplete substringFromIndex: 8];
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"yyyyMMdd"];
NSDate *firstDate = [formatter dateFromString: strFirstDate];
NSDate *secondDate = [formatter dateFromString: strSecondDate];
NSTimeInterval timeInterval = [secondDate timeIntervalSinceDate: firstDate];
you want to parse the number or what? You're sentences are heard to read..
Take a look at NSString's class reference, its fairly easy to break a string up in more parts.
[yourString subStringWithRange:NSMakeRange(location,length)];
Your NSString value contains 2 dates, not one. So you won't be able to use NSDateFormatter
to parse it in one step. You'll need to parse each date separately by first extracting the first 8 characters, then the last 8, using something like [s substringWithRange:NSMakeRange(0,8)]
and [s substringWithRange:NSMakeRange(8,8)]
. Then you can pass these sub-strings into a date formatter using a format like "yyyyMMdd".
精彩评论