rkb
rkb

Reputation: 11231

How do I get the next and earlier date of the current date in iPhone sdk

I have a date object,

NSDate *date = [NSDate date];

Now I want a date earlier of this date and next of it. What function should I use.

Earlier and Later means a day before and a day after.

Also I tried using earlierDate but may be I am using it wrong since it is returning the same date.

tnx.

Upvotes: 2

Views: 2397

Answers (2)

Rog
Rog

Reputation: 17170

You need to use NSCalendar and NSDateComponents to do this calculation reliably.

Here's an example I have to hand to compute an NSDate for noon today. I'm sure you can work out how to get the result you want from this and the documentation.

NSDate *today = [NSDate date];

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
NSDateComponents* todayComponents = [gregorian components:unitFlags fromDate:today];

todayComponents.hour = 12;

NSDate* noonToday = [gregorian dateFromComponents:todayComponents];

Upvotes: 6

Louis Gerbarg
Louis Gerbarg

Reputation: 43452

NSDate is a bit of a misnomer. It is a not a simple date, it is a date a time, with subsecond level precision. The earlierDate: method is a comparison function that returns which ever of the two dates is earlier, it does not create an earlier date. If all you care about is a date that is before your current one you can do:

NSDate *earlierDate = [date addTimeInterval:-1.0];

Which will return a date 1 second before date. Likewise you can do

NSDate *laterDate = [date addTimeInterval:1.0];

for a date 1 second in the future.

If you want a day earlier you can add a days worth of seconds. Of course that is approximate unless you deal with all the gregorian calendar issues, but if you just want a quick approximation:

NSDate *earlierDate = [date addTimeInterval:(-1.0*24*60*60)];

That doesn't work with leap seconds, etc, but for most uses it is probably fine.

Upvotes: 5

Related Questions