I have seen a lot of questions on StackOverflow that appears to be similar but none of them helped me.
I am parsing an RSS Feed and want to covert the date to the "hours ago" format instead of the default one.
else if ([elementName isEqual:@"pubDate"])
{
currentString = [[NSMutableString alloc] init];
NSLog(@"CURRENT STRING %@", currentString); // THIS IS RETURNING NULL IN LOGS
[self setPubTime:currentString]; // But this statement is correctly putting the following in the label in custom tableview cell
}
The last line in the above code is putting the label in the custom cells of tableview as below:
Since the line above is returning NULL in the logs for currentString, i am unable to use the function from this question (iPhone: Convert date string to a relative time stamp) to convert it to the "hours ago" format:
Can somebody point to me why the currentString is empty in the Logs but still able to set the label in next statement and how can i convert it to the hours ago format.
Thanks
UPDATE:
Anupdas's answer has solved half of the problem. Now i can see currentString showing timestamp both in NSLog and the pubTime label inside the custom tableview cell. The only thing that is left is to use this timestamps and convert them to the "hours/min/months etc ago" format.
Using the following:
if ([elementName isEqualToString:@"pubDate"]) {
NSLog(@"pubTime CURRENT IS %@", currentString);
// [self setPubTime:currentString];
NSString *myString = [self dateDiff:currentString];
[self setPubTime:myString];
}
Here is the log after above code:
For some reason, the following function is not working:
-(NSString *)dateDiff:(NSString *)origDate {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"EEE, dd MMM yy HH:mm:ss VVVV"];
NSDate *convertedDate = [df dateFromString:origDate];
[df release];
NSDate *todayDate = [NSDate date];
double ti = [convertedDate timeIntervalSinceDate:todayDate];
ti = ti * -1;
if(ti < 1) {
return @"never";
} else if (ti < 60) {
return @"less than a minute ago";
} else if (ti < 3600) {
int diff = round(ti / 60);
return [NSString stringWithFormat:@"%d minutes ago", diff];
} else if (ti < 86400) {
int diff = round(ti / 60 / 60);
return[NSString stringWithFormat:@"%d hours ago", diff];
} else if (ti < 2629743) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:@"%d days ago", diff];
} else {
return @"never";
}
}
If anyone can point me to a better solution to convert my currentString to "hours/mins/days/ etc format", kindly let me know. Thanks