简体   繁体   English

如何使用 Objective-C 解析日期字符串

[英]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?我如何解析具有此表单“2011052620110529”的 NSString 以将每个值作为 NSString 获取? i tried to write this我试着写这个

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"yyyyMMddyyyyMMdd"];

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:假设每个组件总是 8 个字符长:

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.看看NSString 的 class 参考,它很容易在更多部分中分解字符串。

[yourString subStringWithRange:NSMakeRange(location,length)];

Your NSString value contains 2 dates, not one.您的 NSString 值包含 2 个日期,而不是一个。 So you won't be able to use NSDateFormatter to parse it in one step.因此,您将无法使用NSDateFormatter一步解析它。 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)] .您需要先提取前 8 个字符,然后提取后 8 个字符,分别使用[s substringWithRange:NSMakeRange(0,8)][s substringWithRange:NSMakeRange(8,8)]类的东西来分别解析每个日期。 Then you can pass these sub-strings into a date formatter using a format like "yyyyMMdd".然后,您可以使用“yyyyMMdd”之类的格式将这些子字符串传递给日期格式化程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM