Have a question. I'm working with NSDate and what i need is to get date that was 23 day before. How to do that ? I tried to to something like this:
NSDate *date = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:
(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit)
fromDate:date];
[dateComponents setDay:-23];
[dateComponents setHour:0];
[dateComponents setMinute:0];
[dateComponents setSecond:0];
date = [calendar dateFromComponents:dateComponents];
But its not works...ANy ideas ? tha开发者_StackOverflow中文版nks..
What you need to do is add an NSTimeInterval (which is in seconds) to a newly initialized NSDate instance.
The following code should do the trick:
NSDate* currentDate = [NSDate date];
NSTimeInterval = 60 * 60 * 24 * -23;
NSDate* twentyThreeDaysAgo = [currentDate dateByAddingTimeInterval:timeInterval];
Also note that NSTimeInterval is also just a typedef for a double (it's more readable).
There are alternative ways of producing the same effect. Be sure to check out the NSDate class reference.
Try this,
[dateComponents setDay:[dateComponents day] - 23];
精彩评论