Pregunta

I have start date and a duration (period). For example startDate = '2014-02-12' period = 2. I desired dates 2014-02-12, 2014-02-14, 2014-02-16, .... I need to determine the current date is flagged during.

¿Fue útil?

Solución

To check if the difference between the start date and the current date is an even number of days, use 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
}

Otros consejos

You can get the desired dates using

- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds

with seconds = period*3600*24

Calc the days from startDate to givenData, check the result whether it can be divisible by the period.

+ (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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top