在 Objective-C 中计算两个日期之间的天数 [英] Calculating the number of days between two dates in Objective-C

查看:376
本文介绍了在 Objective-C 中计算两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Possible Duplicate:
How can I compare two dates, return a number of days

I have two dates (as NSString in the form "yyyy-mm-dd"), for example:

NSString *start = "2010-11-01";
NSString *end = "2010-12-01";

I'd like to implement:

- (int)numberOfDaysBetween:(NSString *)startDate and:(NSString *)endDate {

}

解决方案

NSString *start = @"2010-09-01";
NSString *end = @"2010-12-01";

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
                                                    fromDate:startDate
                                                      toDate:endDate
                                                     options:0];

components now holds the difference.

NSLog(@"%ld", [components day]);

这篇关于在 Objective-C 中计算两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆