Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase NSDate +1 day method Objective-C?

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;
}
like image 843
Haris Avatar asked May 23 '11 07:05

Haris


2 Answers

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];
like image 133
Steven Kramer Avatar answered Nov 19 '22 21:11

Steven Kramer


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))
like image 3
x4h1d Avatar answered Nov 19 '22 20:11

x4h1d