【问题标题】:How to check if NSDate is in the specific Month?如何检查 NSDate 是否在特定月份?
【发布时间】:2014-07-18 19:45:18
【问题描述】:

我有一个 NSDates 数组,我想做的是检查日期是否落在一年中的特定月份,并将它们组合在另一个数组中。我得到了 NSInteger 的月份和年份。如果你们能帮助我处理谓词或简单的 if() 语句,那将对我有很大帮助。

【问题讨论】:

  • 为什么不对 NSDates 数组进行排序然后循环遍历它,检查每个日期以查看它所在的月份/年份,然后将它们放入带有 的 NSDictionary 中?跨度>
  • 规范的做法是使用 NSCalendar/NSDateComponents 从每个日期中提取(数字)月份。

标签: ios objective-c nsdate nspredicate


【解决方案1】:

您可以使用下面的函数并为数组制作for循环。

for(NSDate *date in arrDates){

  if([self isDateFalls:date withYourYear:year andYourMonth:month]){
        NSLog(@"YES DATE FALLS IN YEAR AND MONTH");
  } 
  else{
        NSLog(@"NO DATE NOT FALLS IN YEAR AND MONTH");
  }
}

-(BOOL)isDateFalls:(NSDate *)date withYourYear:(NSInteger)year andYourMonth:(NSInteger)month{

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [gregorian components:(NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:date];
    if(dateComponents.year == year && dateComponents.month == month){

        return YES;
    }

    return NO;

}

【讨论】:

    猜你喜欢
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2014-01-20
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多