I am new to iphone development.I am parsing a XML URL and display the title ,date and summary in a table view.I noticed some of the date were very old like "Wed, 31 Dec 1969 19:00:00 -0500" ,So i don't want to display the dates which are 1 year older than the current year.How to do that? I used the sample code from this site for parsing and display the details.Please help me out.Thanks.
Hi there
Dealing with Dates (NSDate Class) is a rather painfull thing to do, and it caused me a lot of trouble and anger.
basically you have different approaches:
1.) get components from your date and compare them to your reference dates.. that could look something like this:
//given that you have an NSDate object called dateOfSearch
unsigned int unitFlags = NSDayCalendarUnit|NSYearCalendarUnit;
NSDateComponents *comp;
NSCalendar *calendar = [NSCalendar currentCalendar];
comp = [calendar components:unitFlags fromDate:dateOfSearch];
NSInteger *year = [comp year];
//year no contains the year that is being contained by the dateOfSearch object. //mind you: this is a basic example to show you how to extract the year of an NSDate Object
2.) use NSDate's timeReferenceSince1970
or other "equivalents" to do comparison (easier)
NSDate's timeReference Methods return the amount of seconds between two referenceDates
so a good approach would be
NSDate *today = [[NSDate alloc] init] //today
NSDate *pastDate = [self getPastDateFromWhereEver];
NSTimeInterval *difference = [pastDate timeIntervalSinceDate:today];
if(difference < .....)
hope that helps
cheers
in addition to samsam's answer and after looking into your sample-code, you have to convert your date-string to a NSDate object:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
NSDate *myDate = [dateFormatter dateFromString:@"Wed, 31 Dec 1969 19:00:00 -0500"];
cheers, marc