gpt4 book ai didi

iphone - iOS : Move forward dynamically NSDate with button

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:50:51 24 4
gpt4 key购买 nike

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

- (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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com