How do I get the next and earlier date of the curr

2020-02-29 23:20发布

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.

标签: iphone
2条回答
在下西门庆
2楼-- · 2020-03-01 00:04

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];
查看更多
乱世女痞
3楼-- · 2020-03-01 00:24

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.

查看更多
登录 后发表回答