Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 286
Dany Avatar asked Nov 15 '11 11:11

Dany


2 Answers

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];
like image 80
Ilanchezhian Avatar answered Sep 30 '22 19:09

Ilanchezhian


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

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

like image 29
dasdom Avatar answered Sep 30 '22 19:09

dasdom