Objective c NSDateComponents工作日不';不显示正确的工作日?
我得到了一个NSDate,例如1/6-12(星期五),并试图找出它是什么工作日。我的一周从周一开始,所以周五应该是工作日5Objective c NSDateComponents工作日不';不显示正确的工作日?,objective-c,ios,ios5,nsdate,nsdatecomponents,Objective C,Ios,Ios5,Nsdate,Nsdatecomponents,我得到了一个NSDate,例如1/6-12(星期五),并试图找出它是什么工作日。我的一周从周一开始,所以周五应该是工作日5 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; [calendar setFirstWeekday:2]; NSDateComponents *components = [calendar components:NS
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[calendar setFirstWeekday:2];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:firstOfJulyDate];
NSLog(@"weekday %i",components.weekday);
输出:工作日6
不管我将setFirstWeekday设置为什么,输出总是6。
我做错了什么?试试这样做:
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setFirstWeekday:2]; // Sunday == 1, Saturday == 7
NSUInteger adjustedWeekdayOrdinal = [gregorian ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:[NSDate date]];
NSLog(@"Adjusted weekday ordinal: %d", adjustedWeekdayOrdinal);
正如NSDateComponents的文档所述: 工作日单位是数字1到n,其中n是一周中的天数。例如,在公历中,n是7,星期日用1表示 此值在使用它的日历的上下文中进行解释,请参见《日期和时间编程指南》中的“日历、日期组件和日历单位” 如果你像预期的那样查看NSGregorianCalendar,它将1-7定义为星期日-星期六 调用setFirstWeekday:2意味着你的一周从周一开始,用于计算是否是一个月的第二周等。这并不意味着你的周一突然变成了周日。2012年6月1日仍然是星期五,而不是星期四,所以你得到的是6,而不是5 如果您想知道从一周开始算起有多少天,而不是工作日,这很简单:
(components.weekday - calendar.firstWeekday + 1) % 7
NSDateComponents不会自动同步所有组件,例如:
NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *component = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSWeekdayCalendarUnit fromDate:date];
currentMonth = component.month;
// printing the next 3 month's start dates MUST have the setYear!
for (int i = currentMonth; i < currentMonth + 3; i++) {
[components setDay:1];
[components setMonth:i];
[components setYear:2014];
NSDate *newDate = [calendar dateFromComponents:components];
NSDateComponents *components2 = [calendar components:NSDayCalendarUnit |NSMonthCalendarUnit | NSWeekdayCalendarUnit fromDate:newDate];
monthInt = [components2 month];
weekIndex = [components2 weekday];
}
NSDate*date=[NSDate-date];
NSCalendar*日历=[NSCalendar currentCalendar];
NSDateComponents*component=[日历组件:NSDayCalendarUnit | NSMonthCalendarUnit | NSWeekdayCalendarUnit fromDate:date];
currentMonth=component.month;
//打印下3个月的开始日期必须具有setYear!
对于(int i=currentMonth;i
确保为日期交叉编码到下一年(在循环之前包括一个简单的if语句)您在工作日的哪里找到文档?我花了30分钟的时间搜索,但找不到任何明确说明索引的引用。