2011-04-20 62 views
1

的问题,我有这样的代码:IOS:与NSDateComponent

- (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月当月有过2个工作日连续的;一个例子:今年在月底的一天,这样的代码写:

.... 25 26 27 28 29 30 30

和30和30是红色的,但它不应该这样,应该是

.... 25 26 27 28 29 30 31

,只有30必须redcolour

为什么发生?

回答

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]; 
} 
+0

我该如何解决? – CrazyDev 2011-04-20 08:54:36

+0

添加了一些代码,并在其中放置了一些版本。 – Eiko 2011-04-20 09:00:47