如何查找存储在2个字符串中的日期之间的天数

时间:2011-03-23 11:58:00

标签: iphone objective-c nsdate nsdateformatter

我有两个字符串都符合以下日期格式(2011-03-22) 我必须比较它们并找出它们之间的天数。

谁能告诉我怎么做......

请告诉我将它们转换回NSDate的正确方法。

2 个答案:

答案 0 :(得分:2)

我可能会输入一些错误,但它本身就说明了,你应该明白这个想法。

NSString *dateStringA = @"2011-03-22";

NSString *dateStringB = @"2011-03-27";

NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = @"yyyy-MM-dd";

NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];

NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates


NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them

答案 1 :(得分:0)

对于字符串到目前为止

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];

日期为字符串

NSString *date = [[NSDate date] description];