我如何知道从现在到应用程序中指定的日期的天数?这是我到目前为止的内容,但是无论日期是什么,每次都会显示“-30”:

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

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit
                                                              fromDate:DatePicker.date];

CalLabel1.text = [NSString stringWithFormat:@"%d", [components day]];

NSDateFormatter *temp = [[NSDateFormatter alloc] init];
[temp setDateFormat:@"dd/MM/yyyy"];
NSDate *stDt = [temp dateFromString:[temp stringFromDate:[NSDate date]]];
NSDate *endDt =  [temp dateFromString:[temp stringFromDate:[NSString stringWithFormat:@"%d", [components date]]]];
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:stDt  toDate:endDt  options:0];
int days = [comps day];

NSLog(@"%i", [comps day]);

最佳答案

NSDate * selected = [DatePicker date];
NSCalendar *gregorian = [[NSCalendar alloc]
                          initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components: NSDayCalendarUnit
                                       fromDate: [NSDate date]
                                         toDate: selected
                                        options: 0];
int days = [comps day];

NSLog(@"%i", [comps day]);

这将计算从现在到所选日期的天数。您对日期格式化程序的所有弄乱都是错误的,没有必要。

关于iphone - 如何知道从现在起到NSDate的天数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7959243/

10-08 21:05