Iphone 比较NSDate和x2B;时期

Iphone 比较NSDate和x2B;时期,iphone,objective-c,nsdate,Iphone,Objective C,Nsdate,我有开始日期和持续时间(期间)。例如startDate='2014-02-12'period=2。我希望的日期是2014-02-12,2014-02-14,2014-02-16。。。。我需要确定期间标记的当前日期。您可以使用 -(id)dateByAddingTimeInterval:(NSTimeInterval)秒 使用seconds=period*3600*24检查开始日期和当前日期之间的差值是否为偶数 天数,使用NSDateComponents: NSDate *startDate =

我有开始日期和持续时间(期间)。例如
startDate='2014-02-12'
period=2
。我希望的日期是2014-02-12,
2014-02-14
2014-02-16
。。。。我需要确定期间标记的当前日期。

您可以使用

-(id)dateByAddingTimeInterval:(NSTimeInterval)秒


使用
seconds=period*3600*24

检查开始日期和当前日期之间的差值是否为偶数 天数,使用
NSDateComponents

NSDate *startDate = ...;
NSDate *currentDate = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *diff = [cal components:NSDayCalendarUnit fromDate:startDate
                                  toDate:currentDate options:0];
NSInteger days = diff.day;
if (days % 2 == 0) {
    // even number of days between start date and current date
}

计算从startDate到givenData的天数,检查结果是否可以被周期整除

+ (NSInteger)daysWithinEraFromDate:(NSDate *)startDate toDate:(NSDate *)endDate {
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setTimeZone:[NSTimeZone localTimeZone]];
    // for timezone issue
    NSDate *newDate1 = [startDate dateByAddingTimeInterval:[[NSTimeZone localTimeZone] secondsFromGMT]];
    NSDate *newDate2 = [endDate dateByAddingTimeInterval:[[NSTimeZone localTimeZone] secondsFromGMT]];
    NSInteger startDay = [gregorian ordinalityOfUnit:NSDayCalendarUnit
                                            inUnit: NSEraCalendarUnit forDate:newDate1];
    NSInteger endDay = [gregorian ordinalityOfUnit:NSDayCalendarUnit
                                          inUnit: NSEraCalendarUnit forDate:newDate2];
    return endDay - startDay;
}

能否添加一些示例代码?开始日期是NSDate还是NSString?你试过什么?“标记当前日期”是什么意思?起始日期为NSDate。如果当前日期等于2014年2月12日、2014年2月14日、2014年2月16日……编号。不是每天都有24小时。考虑夏令时转换。请注意,
components:fromDate:toDate:options:
method将计算结果截断为提供的最小单位。例如,如果fromDate:参数对应于2010年1月14日晚上11:30,而toDate:参数对应于2010年1月15日上午8:00,则两个日期之间只有8.5小时。如果你问天数,你会得到0,因为8.5小时少于1天。在某些情况下,这应该是1天。您必须决定用户在特定情况下期望的行为。如果您需要两个日期之间的天数,请查看我的答案,如两个日期之间的午夜数。@lancy:您是对的,我假设
startDate
是第一天(00:00)的开始。如果不是这种情况,则可以使用
[cal rangeOfUnit:NSDayCalendarUnit startDate:&BeginingOfStartDate interval:NULL forDate:startDate]轻松实现