我有这段代码:
- (void) setDataLabel{
for (int k = 0; k<31; k++){
[[lineSunday objectAtIndex:k] setAlpha:0.00];
[[arrayDay objectAtIndex:k] setTextColor:[UIColor whiteColor]];
}
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:2011];
[components setDay:1];
[components setMonth:10];
//NSLog(@"mese:%d", month);
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *firstDate = [gregorianCalendar dateFromComponents:components];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
for (int i = 0; i < 31; i++) {
NSTimeInterval seconds = 24*60*60 * i;
NSDate *date = [NSDate dateWithTimeInterval:seconds sinceDate:firstDate];
NSDateComponents *weekdayComponents = [gregorianCalendar components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
NSString *strDate = [dateFormatter stringFromDate: date];
[[arrayDay objectAtIndex:i] setText:strDate];
if (weekday == 1) {
[[arrayDay objectAtIndex:i] setTextColor:[UIColor redColor]];
[[lineSunday objectAtIndex:i] setAlpha:1.00];
}
}
此代码设置31个标签,包含该月的日期,一切正常,但我不明白为什么10月份有连续两个工作日;一个例子:在今年,这段代码以这种方式写在当天月底:
.... 25 26 27 28 29 30 30
和30和30是红色,但它不应该是,它应该是
.... 25 26 27 28 29 30 31
只有30个必须是redcolour
为什么会这样?
答案 0 :(得分:1)
这是因为夏令时。我们在该循环中每天添加86400秒,但有一天将有25小时。
编辑:
最佳方法可能只是在循环中获取日期对象,而不是进行花哨的计算。
- (void) setDataLabel{
for (int k = 0; k<31; k++){
[[lineSunday objectAtIndex:k] setAlpha:0.00];
[[arrayDay objectAtIndex:k] setTextColor:[UIColor whiteColor]];
}
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setYear:2011];
[components setMonth:10];
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
for (int i = 0; i < 31; i++) {
[components setDay:i+1];
NSDate *date = [gregorianCalendar dateFromComponents:components];
NSDateComponents *weekdayComponents = [gregorianCalendar components:NSWeekdayCalendarUnit fromDate:date];
int weekday = [weekdayComponents weekday];
NSString *strDate = [dateFormatter stringFromDate: date];
[[arrayDay objectAtIndex:i] setText:strDate];
if (weekday == 1) {
[[arrayDay objectAtIndex:i] setTextColor:[UIColor redColor]];
[[lineSunday objectAtIndex:i] setAlpha:1.00];
}
}
[dateFormatter release];
[gregorianCalendar release];
[components release];
}