我想使用周末的日期在 NSLocalNotification 中使用它,但我不知道如何得到它,我试图用数学方法来做,但有时我得到的数字大于一个月中的天数。
问问题
216 次
2 回答
1
请注意,iOS 支持多个日历,我不确定是否所有使用这些日历的文化都有周末的概念,并且它们是否总是意味着有两天。
您还需要处理一些事情:即使在使用公历的国家,一周也可能从星期一或星期日开始。
但是,如果我们假设周末相当于周六和周日,这可能对您有所帮助:
NSDate *referenceDate = [NSDate date];
NSDate *startOfThisWeek;
NSDate *saturday;
NSUInteger backupStartWeekday = [[NSCalendar currentCalendar] firstWeekday];
[[NSCalendar currentCalendar] setFirstWeekday:1]; // ensure week begins at sunday
[[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit
startDate:&startOfThisWeek
interval:NULL
forDate:referenceDate];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit].length; //the start of the next week
components.day = components.day - 2;
saturday = [[NSCalendar currentCalendar] dateByAddingComponents:components
toDate:startOfThisWeek
options:0];
[[NSCalendar currentCalendar] setFirstWeekday:backupStartWeekday];
于 2012-12-17T08:02:37.357 回答
0
关于获取日期的第一个问题可以解决为:
NSCalendar *calender=[NSCalendar currentCalendar];
NSRange daysRange=[calender rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
NSUInteger numberOfDaysInMonth=daysRange.length;
//NSLog(@"num of days in current month : %ld",numberOfDaysInMonth);
NSDateComponents *dateComponents = [calender components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
NSInteger dayCount=[dateComponents weekday];
//if today itself is saturday what you want to display? today or upcoming one... then do small changes here, for sat & sun.
NSInteger daysForSaturday=7-dayCount;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd"];
NSUInteger todaysDate = [[formatter stringFromDate:[NSDate date]]integerValue];
// NSLog(@"Today is : %@",todaysDate);
NSUInteger comingSaturday=todaysDate+daysForSaturday;
if (comingSaturday>numberOfDaysInMonth) {
comingSaturday-=numberOfDaysInMonth;
}
NSUInteger comingSunday=comingSaturday+1;
NSLog(@"Coming.. Sat is : %ld, Sun in : %ld",comingSaturday, comingSunday);
于 2012-12-17T07:35:33.290 回答