user1066006
user1066006

Reputation: 135

Get NSDate for current date - 3 months

How can I get the current date - 3 months? I need it for a database query to get all files in the last 3 months.

I know the operation "dateByAddingTimeInterval" but I would have to subtract the 3 months instead.

Upvotes: 0

Views: 572

Answers (1)

user387184
user387184

Reputation: 11053

Depending how you define 3 month. If you mean the same day 3 months ago you could do sth like this:

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit |NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]];

    NSInteger now_hour = [components hour];
    NSInteger now_minute = [components minute];
    NSInteger yearx =  [components year];
    NSInteger monthx =  [components month];
    NSInteger dayx =  [components day];

    //1 = january
    NSInteger monthsMinus3 = (monthx > 3) ? monthx -3 : (monthx +12 -3);
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setMinute:now_minute];
    [comps setHour:now_hour];
    [comps setYear:yearx];
    [comps setMonth:monthx];
    [comps setDay:dayx];
    NSDate *threeMonthAgo = [calendar dateFromComponents:comps];

of course you could also change the month without having to create the extra date, but I thought thi is clearer and more flexible, in case you like to debug and possible change days as well, in case you define 3 months ago by -n days depending in which month we are. eg - (30+31+30), or -(31+30+31) or having to account for februray 28 days.

Again, all depends how you define 3 months ago... but this should lead you to the solution

Upvotes: 1

Related Questions