2013-10-21 20 views
1

我在寫報警應用程序。在應用程序中,用戶可以隨時選擇日期來設置當天的鬧鐘。但我不知道在一週內的特定日期設置UILocalNotification。特定日期的個性化信息

我如何知道重複間隔。我知道我必須設置

如何計算星期五會有多少天?

回答

0

How to Get an NSDate for a Specific Day of Week and Time from an Existing NSDate - 本文將幫助你解決這個問題。您可以從當前週五得到的NSDate:

NSDate *today = [NSDate date]; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
[gregorian setLocale:[NSLocale currentLocale]]; 
  
NSDateComponents *nowComponents = [gregorian components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:today]; 
  
[nowComponents setWeekday:6]; 
[nowComponents setWeek: [nowComponents week]]; // Current week 
[nowComponents setHour:8]; // 8a.m. 
[nowComponents setMinute:0]; 
[nowComponents setSecond:0]; 
  
NSDate *thisWeekFriday = [gregorian dateFromComponents:nowComponents]; 

然後,你可能要檢查是否thisWeekFriday小於[NSDate date],並獲得下週五,如果它是。您可以將日期移動一週:

NSDateComponents *components = [[NSDateComponents alloc] init]; 
components.week = 1; 
NSDate *nextWeekFriday = [gregorian dateByAddingComponents:components toDate:thisWeekFriday options:0]; 
+0

今天是星期二。我將通知設置爲星期一,並且工作正常。爲什麼?如何僅在下個星期一設置通知? –

+0

@BogdanKorda:我已經更新了我的答案。 –

0

可以計算天數兩個日期之間是這樣的:

NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit 
                    fromDate:today 
                    toDate:futureDate 
                    options:0]; 
NSInteger daysBetweenDates = dateComponents.day;