如何判断从现在到NSDate的天数?

时间:2011-10-31 20:17:00

标签: iphone objective-c ios xcode nsdate

如何判断从现在到我的应用中指定的日期的天数?这是我到目前为止所拥有的,但无论日期是什么,它每次都会出现“-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]);

3 个答案:

答案 0 :(得分:7)

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]);

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

答案 1 :(得分:3)

如何在-timeIntervalSinceNow上使用NSDate

NSDate *selectedDate = [datePicker date];
NSTimeInterval numberOfSecondsUntilSelectedDate = [selectedDate timeIntervalSinceNow];
NSInteger numberOfDays = numberOfSecondsUntilSelectedDate / 86400; // 86,400 seconds in a day

答案 2 :(得分:1)

接受答案的Swift 3版本。

let dateComponents = Calendar.current.dateComponents([.day], from: fromDate, to: Date())

// number of days is an optional Int
if let daysCount = dateComponents.day {
    print(daysCount)
}