2012-08-15 68 views
0

如何获取当前日期 - 3个月?我需要它来进行数据库查询以获取最近3个月内的所有文件。获取当前日期的NSDate - 3个月

我知道操作“dateByAddingTimeInterval”,但我将不得不减去3个月。

回答

1

取决于你如何定义3个月。如果3个月前的意思是在同一天,你可以做某事像这样:

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]; 
当然

你也可以更改月份,而无需创建额外的日期,但我认为THI是更清晰,更灵活,你喜欢调试的情况以及可能的更改日期,以防你在3个月前定义-n天,这取决于我们是哪个月。例如 - (30 + 31 + 30)或 - (31 + 30 + 31),或者必须考虑二十八天的二十四小时。

再说一次,一切都取决于你3个月前如何定义......但这应该引导你找到解决方案

相关问题