简体   繁体   中英

Compare dates of a month with an array

In my app i am showing, the list of months in table view. For each month there are few events in it for some dates. So my question is how to compare the dates in my array with the dates of month to show the events in their respective months only.

you can use NSDateComponents for that:

NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = 
      [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:yourDate];

[components month];// gives you month 

Compare this month with the Array index for example or another way you prefer.

In your case probably you only need to compare the year and month component of the date. There's probably many ways for implementing this. This is what i would have tried. Convert your date in tableview in yyyy-MM Format and also the event dates in the same format probably the way given below.

NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:@"yyyy-MM"];
dateFormatter1.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSDate *monthDate=[NSDate date];
NSString *strMonthDate=[dateFormatter1 stringFromDate:monthDate];
NSLog(@"%@",strMonthDate);

Compare this monthDate string with your eventDate string using normal NSString comparison methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM