一周内更改日期而不是明天

时间:2016-01-01 15:40:43

标签: ios objective-c date

这里我使用Some label来显示日期。我有2个箭头按钮可以向后移动和之前的日期。如下所示:

   (button)  < **27Dec 28Dec 29Dec 30Dec 31Dec 1Jan** >(Button)

以下是代码:

- (void)viewDidLoad {
    [super viewDidLoad];
firstdate = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay value:-5 toDate:[NSDate date] options:nil];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM,yyyy"];
    dateLabel.text = [dateFormat stringFromDate:[NSDate date]];
    dateLabel.text = [dateFormat stringFromDate: firstdate];

    [self dateChange];
}
-(void)dateChange
{
    NSArray *labelArray = @[flabel, slabel, tlabel, folabel, fivlabel,sixlabel];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    dateFormatter.dateFormat = @"ddMMM";
    for (NSInteger i = 0; i < 6; ++i) {
        NSDate *nextDate = [calendar dateByAddingUnit:NSCalendarUnitDay value:i toDate:firstdate options:nil];
        UILabel *label = (UILabel *)labelArray[i];
        label.text = [dateFormatter stringFromDate:nextDate];
        if (i==5) {
            dateFormatter.dateFormat=@"MMM,yyyy";
            dateLabel.text = [[dateFormatter stringFromDate:nextDate] capitalizedString];

            NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
            [dateFormat setDateFormat:@"yyyy-MM-dd"];

            if ([[dateFormat stringFromDate:nextDate] isEqualToString:[dateFormat stringFromDate:[NSDate date]]])
            {
                leftBtn.enabled = false;
                //It's the same day
            }
            else
            {
                leftBtn.enabled = true;
            }
        }
    }
}
- (IBAction)calRight:(id)sender {

    firstdate = [NSDate dateWithTimeInterval:86400 sinceDate:firstdate];
    [self dateChange];


}

- (IBAction)calLeft:(id)sender {
 firstdate = [NSDate dateWithTimeInterval:-86400 sinceDate:firstdate];
    [self dateChange];
}

上面的代码就像按下后退按钮一样,它会逐个更改日期:

     < **27Dec 28Dec 29Dec 30Dec 31Dec 1Jan** >

现在,如果我按左箭头:

  < **26Dec 27Dec 28Dec 29Dec 30Dec 31Dec** >

但是当我按下左箭头或右箭头时,我需要按照这样的方式逐周进行:

 < **27Dec 28Dec 29Dec 30Dec 31Dec 1Jan** >

现在,如果我按左箭头:

  < **21Dec 22Dec 23Dec 24Dec 25Dec 26Dec** >

现在,如果我再次按向左箭头,它应该是这样的:

 < **16Dec 16Dec 17Dec 18Dec 19Dec 20Dec** >

请问我需要改变什么来改变星期的日期。请帮助我!

1 个答案:

答案 0 :(得分:0)

如果您希望按钮将firstDate更改为7天而不是1天,请将按钮方法更改为:

- (IBAction)calRight:(id)sender {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    firstdate = [calendar dateByAddingUnit:NSCalendarUnitDay value:7 toDate:firstdate options:nil];
    [self dateChange];
}

- (IBAction)calLeft:(id)sender {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    firstdate = [calendar dateByAddingUnit:NSCalendarUnitDay value:-7 toDate:firstdate options:nil];
    [self dateChange];
}

注意:使用86400的当前代码不好。切勿使用此类代码进行日期数学运算。