我需要知道NSDate在哪一周出现。我知道weekOfMonth,month和year。
例如,如果我的weekOfMonth是0,month是2,year是2016。我想获取当前周(从周日到周六)的可用日期。但由于本周的第一天(星期日)正好是上个月,我需要获取2016年2月1日到2016年2月6日(星期一到星期六)的日期。
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.month = components.month;
comp.year = components.year;
comp.day = ??; // What should I give here to get the current start date of the week?或者,如果我能知道本周的开始日期和结束日期,那也会很有帮助。
发布于 2016-02-03 07:25:23
下面是一种略显笨拙的方法,它基于使用dayOfWeek = 0获取日期,然后继续前进,直到结果日期在同一个月内
int monthTarget = 2;
int dayOfWeekTarget = 0;
int yearTarget = 2016;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comp = [[NSDateComponents alloc] init];
[comp setMonth:monthTarget];
[comp setYear:yearTarget];
[comp setWeekOfMonth:dayOfWeekTarget];
[comp setDay:dayOfWeekTarget];
// see what this gives us
NSDate *firstDate = [calendar dateFromComponents:comp];
NSDateComponents *firstDayComponents = [calendar components:NSCalendarUnitMonth | NSCalendarUnitDay fromDate:firstDate];
NSInteger day = [firstDayComponents day];
NSInteger month = [firstDayComponents month];
// move forward if we have to
while (month < monthTarget)
{
dayOfWeekTarget++;
[comp setDay:dayOfWeekTarget];
firstDate = [calendar dateFromComponents:comp];
firstDayComponents = [calendar components:NSCalendarUnitMonth | NSCalendarUnitDay fromDate:firstDate];
day = [firstDayComponents day];
month = [firstDayComponents month];
}我相信您可以稍微整理一下,但是方法就在这里!
https://stackoverflow.com/questions/35155135
复制相似问题