Objective c 增加NSDate+;1天方法目标-C?
这是我在导航栏中增加一天的方法,并将当天的名称设置为标题。我知道这是错误的,因为每次调用“today”变量时我都设置了它。但每次调用此方法时,我都不知道如何增加+1天Objective c 增加NSDate+;1天方法目标-C?,objective-c,cocoa-touch,nsdate,Objective C,Cocoa Touch,Nsdate,这是我在导航栏中增加一天的方法,并将当天的名称设置为标题。我知道这是错误的,因为每次调用“today”变量时我都设置了它。但每次调用此方法时,我都不知道如何增加+1天 -(void)stepToNextDay:(id)sender { today = [NSDate date]; NSDate *datePlusOneDay = [today dateByAddibgTimeInterval:(60 * 60 * 24)]; NSDateFormatter *datefo
-(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;
}
将显示的日期存储在视图控制器的属性(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];
从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))
在导航栏中,我有两个按钮,用于浏览一周中的每一天。当我想显示“第二天”时,调用此方法。每天我都会浏览到我从Web服务请求数据并填充tableviewCell。你很幸运,我今天感觉很有帮助:)