Dany
Dany

Reputation: 2290

Obtain yesterday with NSDate in objective-c

I need to obtain the date of yesterday with NSDate object. Any idea?

EDIT : SOLVED:

NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-86400];

Upvotes: 9

Views: 9608

Answers (2)

dasdom
dasdom

Reputation: 14063

NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow: -(60.0f*60.0f*24.0f)];

Edit: This solution isn't correct. See Aadhiras answer for the correct solution.

Upvotes: 8

Ilanchezhian
Ilanchezhian

Reputation: 17478

Try this code. With this way, you can get next days, next months, previous days , previous months..

NSDate *now = [NSDate date];
int daysToAdd = -1;  

// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];

// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSDate *yesterday = [gregorian dateByAddingComponents:components toDate:now options:0];
NSLog(@"Yesterday: %@", yesterday);
[gregorian release];

Upvotes: 47

Related Questions