iphone - iOS : Move forward dynamically NSDate with button

标签 iphone ios xcode ipad sdk

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

- (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 dateByAddingComponents:offsetComponents 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];

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

最佳答案

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

- (IBAction)moveDatesForward:(id)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 dateByAddingComponents:offsetComponents 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/

相关文章:

iphone - 从 xcode 调用 FFMPEG 命令

iphone - 如何使用 GData 对 iPhone 上的 Google 用户进行身份验证?

ios - 一侧有阴影/边框和圆角的 iPhone UIButton

android - 在用户从网页转到应用程序后跟踪用户

ios - MPMediaItemArtwork 和透明度

ios - 在 iOS Swift 3 中使用 UISplitViewController

iphone - iOS 部署目标缺失

iphone - 将字节值放入 NSDictionary [iOS]

ios - CALayer.timeOffset 何时可以使用

iphone - 在视网膜显示器上使用实际像素绘图