OStack程序员社区-中国程序员成长平台

标题: iphone - iOS : Move forward dynamically NSDate with button [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 18:57
标题: iphone - iOS : Move forward dynamically NSDate with button

我已经为我的日期创建了一个自定义类,并且需要通过按钮向前和向后移动日期。这是我显示今天日期的代码:

- (NSString *) showToday {

    NSCalendar *myCal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setCalendar:myCal];

    offsetComponents = [[NSDateComponents alloc] init];
//shows today 
    [offsetComponents setDay:0];

    NSDate *nextDate = [myCal dateByAddingComponentsffsetComponents toDate:[NSDate date] options:0];

    [dateFormatter setDateFormat"d"];
    NSString *currDay = [dateFormatter stringFromDate:nextDate];

    [NSString stringWithFormat"%@",currDay];

    [myCal release];
    [dateFormatter release];
    return currDay;
}

在我的 viewController 上:

customClass = [[customClass alloc]init];

    day.text = [cal showToday];

所以如果我需要提前一个日期,我只需将此行代码更改为:

//show tomorrow 
[offsetComponents setDay:1];

那么如何通过按钮动态更改此行并更改日期?



Best Answer-推荐答案


您可以为您的 offsetComponents 变量声明一个 int。然后:

- (IBAction)moveDatesForwardid)sender {

    NSCalendar *persCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSPersianCalendar];    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *IRLocal = [[NSLocale alloc] initWithLocaleIdentifier"fa_IR"];
    [dateFormatter setLocale:IRLocal];
    [dateFormatter setCalendar:persCalendar];

    offsetComponents = [[NSDateComponents alloc] init];

    offsetComponents.day = _dayNumber;

    NSDate *nextDate = [persCalendar dateByAddingComponentsffsetComponents toDate:[NSDate date] options:0];

    [dateFormatter setDateFormat"d"];
    dayLabel.text = [dateFormatter stringFromDate:nextDate];

    [NSString stringWithFormat"%@",dayLabel];

    [persCalendar release];
    [dateFormatter release];

      _dayNumber ++;

}

关于iphone - iOS : Move forward dynamically NSDate with button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8934983/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4