9

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

EDIT : SOLVED:

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

Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
Dany
  • 2,290
  • 8
  • 35
  • 56

2 Answers2

46

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];
Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55
  • 6
    +1 this is a better answer. Adding or subtracting 86400 seconds can give the WRONG answer if today or yesterday is the day where local time changes from Daylight Savings to Standard Time (or vice versa) depending on the time of day you perform that operation. – progrmr Nov 24 '11 at 14:20
9
NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow: -(60.0f*60.0f*24.0f)];

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

dasdom
  • 13,975
  • 2
  • 47
  • 58
  • 1
    `NSTimeInterval` is a double, so you can get rid of the `f`. Although the compiler does this most likely also for you. – JustSid Nov 15 '11 at 11:15
  • When I don't need the precision I like to tell the compiler that float is enough because, as far as I know, the iPhone processor can't handle double as good as float. – dasdom Nov 15 '11 at 11:18
  • 1
    Depends on the generation, but the compiler will most likely solve the equation already fix in place and even if it didn't three multiplications aren't that expensive! There are way better places to do micro-optimization. – JustSid Nov 15 '11 at 12:09