如何判断从现在到 NSDate 的天数? [英] How to tell the amount of days from now until an NSDate?
本文介绍了如何判断从现在到 NSDate 的天数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何知道从现在到我的应用中指定的日期的天数?这是我到目前为止所拥有的,但每次都会出现-30",无论日期是什么:
How can I tell the amount of days from now until the date specified in my app? Here is what I have so far, but it comes up with "-30" every time, no matter what the date is:
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]);
这会计算从现在到所选日期之间的天数.您对日期格式化程序的所有弄乱都是错误的,而且没有必要.
This calculates the number of days between now and the selected date. All your messing around with the date formatter was wrong and not necessary.
这篇关于如何判断从现在到 NSDate 的天数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文