Increase NSDate +1 day method Objective-C?

笑着哭i 提交于 2019-11-27 02:44:00

问题


This is my method I use for increasing by one day in my navigationBar, and setting the name of the day as a title. I know it's wrong because I set "today" variable every time its called. But I can't figure out how to increase +1 day every time I call this method.

-(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;
}

回答1:


Store the date your are showing in a property (ivar, ...) of your view controller. That way you can retrieve the current setting when you go to the next day.

If you want to reliably add dates, use NSCalendar and NSDateComponents to get a "1 day" unit, and add that to the current date.

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];



回答2:


As from iOS 8 NSGregorianCalendar is depricated, the updated answer will be,

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *newDate = [calendar dateByAddingComponents:components toDate:today options:0];

Swift Code:

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))


来源:https://stackoverflow.com/questions/6094403/increase-nsdate-1-day-method-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!