2013-10-09 3 views
-1

У меня есть компонент даты сказать birthdayComponent (он имеет месяц и день в нем), и я хочу проверить, находится ли он между другими компонентами .. say (beginDaYComponent и endDayComponent).Как проверить, существует ли день между двумя другими днями в iOS ...?

Я хочу проверить, находится ли мой компонент дня рождения между этими двумя датами ..? Как я могу достичь этого, так как я также должен учитывать граничные случаи, скажем 29 февраля, и у меня будут значения endDayCompnents как 3 для месяца и 1 для дня. Вы можете ознакомиться с приведенным ниже кодом для получения дополнительной информации.

NSDateFormatter *dateFormat = [NSDateFormatter new]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd"]; 

    NSDateComponents *dayComponent = [[NSDateComponents alloc] init]; 
    NSDateComponents *beginDayComponent = [[NSDateComponents alloc] init]; 
    NSDateComponents *endDayComponent = [[NSDateComponents alloc] init]; 

    NSCalendar *theCalendar = [NSCalendar currentCalendar]; 
    NSMutableArray* birthdayFitlerArray = [NSMutableArray new]; 

    for (NSString* dateString in birthdaysArray) 
    { 
     NSDate* birthdayDate = [dateFormat dateFromString:dateString]; 

     dayComponent.day = -1; 
     NSDate* beginDate = [theCalendar dateByAddingComponents:dayComponent toDate:currentLeg.date options:0]; 

     dayComponent.day = 1; 
     NSDate* endDate = [theCalendar dateByAddingComponents:dayComponent toDate:currentLeg.date options:0]; 

     beginDayComponent = [theCalendar components:(NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:beginDate]; 
     endDayComponent = [theCalendar components:(NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:endDate]; 

     NSDateComponents* birthdayComponents = [theCalendar components:(NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:birthdayDate]; 

} 

UPDATE:

Я хочу исключить из компонент год для даты.

+1

быстро прибегая к помощи: 'сравнить NSDate без year' и [это придумал] (http://stackoverflow.com/a/6252686/1387438) –

+0

@MarekR: близко, но не то же самое. то есть без временной части. – vikingosegundo

ответ

3

Создайте два объекта NSDate, которые вы хотите использовать в качестве верхней и нижней границ.

Затем используйте метод сравнения NSDate, чтобы узнать, находится ли ваша дата между двумя датами. Вам нужно использовать метод сравнения дважды. Проверьте compare method's documentation:

  • Приемник и anotherDate точно равны друг другу, NSOrderedSame
  • Приемник позже во времени, чем anotherDate, NSOrderedDescending
  • Приемник раньше во времени, чем anotherDate, NSOrderedAscending ,
+0

проблема заключается в том, что она также будет сравнивать годовую часть даты .., которую я не хочу сравнивать, поскольку мне просто нужно проверить, находится ли день рождения между двумя датами. –

+0

Почему бы вам не установить все из них быть в текущем году? –

+0

Спасибо .. это то, что я закончил делать. –

1
NSDateComponents *firstDayDateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:randomdate]; 
[firstDayDateComponents setDay:1]; // set what you want here 
[firstDayDateComponents setHour:0]; 
[firstDayDateComponents setMinute:0]; 

NSComparisonResult result = [randomdate compare:date_today]; 

if (result == NSOrderedAscending) // if today's date is bigger than randomdate) 
{ 
    // do stuff here 
} 

я думаю, что это довольно просто здесь :)

0
NSDate *startDate = …; 
NSDate *endDate = …; // make sure endDate is later than startDate 
NStimeInterVal endInterval; 

[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&startDate interval:NULL forDate:startDate]; 
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&endDate interval:&endInterval forDate:endDate]; 
endDate = [endDate dateByAddingTimeInterval:endInterval-0.001]; 

Это позволит создать начальную дату для времени 0:00 и endate от 23: 59: 59.999 в значение по умолчанию часовой пояс

Теперь используем метод сравнения

if ([givenDate compare:startDate] == NSOrderedAscending){ 
    //date is before both dates 
} else if ([givenDate compare:endDate] == NSOrderedDescending){ 
    // date lies after both dates 
} else { 
//givenDate lies between both dates. 
} 

стало очевидно, что вы хотите проверить его на год. Просто установите yer на год - например, 1 - для сравнения для всех задействованных дат.

NSDateComponents *comps = [aCalendar components:(NSUIntegerMax - NSYearCalendarUnit) fromDate:date]; 
comps.year = 1; 
NSDate *year1Date = [aCalendar dateFromComponents:comps]; 

NSDate *startDate = …; 
NSDate *endDate = …; // make sure endDate is later than startDate 
NStimeInterVal endInterval; 

NSDateComponents *comps = [aCalendar components:(NSUIntegerMax - NSYearCalendarUnit) fromDate:startDate]; 
comps.year = 1; 
NSDate *year1StartDate = [aCalendar dateFromComponents:comps]; 

comps = [aCalendar components:(NSUIntegerMax - NSYearCalendarUnit) fromDate:endDate]; 
comps.year = 1; 
NSDate *year1EndDate = [aCalendar dateFromComponents:comps]; 

comps = [aCalendar components:(NSUIntegerMax - NSYearCalendarUnit) fromDate:givenDate]; 
comps.year = 1; 
NSDate *year1givenDate = [aCalendar dateFromComponents:comps]; 


[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&year1StartDate interval:NULL forDate:year1StartDate; 
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&endDate interval:&endInterval forDate:endDate]; 
endDate = [endDate dateByAddingTimeInterval:endInterval-0.001]; 

if ([year1givenDate compare:year1StartDate] == NSOrderedAscending){ 
    //date is before both dates 
} else if ([year1givenDate compare:year1EndDate] == NSOrderedDescending){ 
    // date lies after both dates 
} else { 
//givenDate lies between both dates. 
} 
0

Довольно просто. Вы можете использовать метод laterDate:NSDate или оба earlierDate: и laterDate:. Пожалуйста, прочитайте описание об этих методах.

// 1. 
NSDate *firstDate, *secondDate, *thirdDate; 

if ([firstDate laterDate:secondDate] == secondDate && 
    [secondDate laterDate:thirdDate] == thirdDate) 
{ 
    /// secondDate is between first and third date. 
} 

// 2. 
if ([secondDate earlierDate:firstDate] == firstDate && 
    [secondDate laterDate:thirdDate] == thirdDate) 
{ 
    /// secondDate is between first and third date. 
}