这是我用于在navigationBar中增加一天的方法,并将当天的名称设置为标题。我知道这是错的,因为我每次调用时都设置“今天”变量。但是每次调用这种方法时我都无法弄清楚如何增加+1天。
-(void)stepToNextDay:(id)sender
{
today = [NSDate date];
NSDate *datePlusOneDay = [today dateByAddibgTimeInterval:(60 * 60 * 24)];
NSDateFormatter *dateformatterBehaviour = [[[NSDateFormatter alloc]init]autorelease];
[dateFormatter setDateFormat:@"EEEE"];
NSString *dateString = [dateFormatter stringFromDate:datePlusOneDay];
self.navigationItem.title = datestring;
}
答案 0 :(得分:30)
将您所显示的日期存储在视图控制器的属性(ivar,...)中。这样,当你去第二天时,你可以检索当前的设置。
如果要可靠地添加日期,请使用NSCalendar和NSDateComponents获取“1天”单位,并将其添加到当前日期。
NSCalendar* calendar = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar] autorelease];
NSDateComponents* components = [[[NSDateComponents alloc] init] autorelease];
components.day = 1;
NSDate* newDate = [calendar dateByAddingComponents: components toDate: self.date options: 0];
答案 1 :(得分:3)
从iOS 8 NSGregorianCalendar
不推荐使用,更新后的答案为
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *newDate = [calendar dateByAddingComponents:components toDate:today options:0];
Swift代码:
var today:NSDate = NSDate()
let calender:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
var components:NSDateComponents = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.CalendarUnitDay)
var newDate:NSDate! = calender.dateByAddingComponents(components, toDate:today, options: NSCalendarOptions(0))