i have a methods :
- (NSString *)intervalSinceNow: (NSString *) theDate
{
NSDateFormatter *date=[[NSDateFormatter alloc] init];
[date setDateFormat:@"yyyy-MM-dd HH:mm "];
NSDate *d=[date dateFromString:theDate];
NSTimeInterval late=[d timeIntervalSince1970]*1;
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval now=[dat timeIntervalSince1970]*1;
NSString *timeString=@"";
NSTimeInterval cha=now-late;
if (cha/3600<1) {
timeString = [NSString stringWithFormat:@"%f", cha/60];
timeString = [timeString substringToIndex:timeString.length-7];
timeString=[NSString stringWithFormat:@"%@m before", timeString];
}
if (cha/3600>1&&cha/86400<1) {
timeString = [NSString stringWithFormat:@"%f", cha/3600];
timeString = [timeString substringToIndex:timeString.length-7];
timeString=[NSString stringWithFormat:@"%@ hour before", timeString];
}
if (cha/86400>1)
{
timeString = [NSString stringWithFormat:@"%f", cha/86400];
timeString = [timeString substringToIndex:timeString.length-7];
timeString=[NSString stringWithFormat:@"%@ day before", timeString];
}
return timeString;
}
when i call intervalSinceNow(2012-07-04T00:16:12Z) it give me 15525 day before,how to solves,thank you?
It’s best not to even try to do these calculations yourself. You have no idea what calendar system the local user is using, among other things.
The steps to do what you want on the system are as follows:
– Convert the ISO8601 datetime to an instance of NSDate
– Display the NSDate in the user’s locale and local time zone
These steps can be accomplished by using two
NSDateFormatterobjects. One set up to convert the datetime string into an NSDate and configured for Zulu and the other to format the date for the user’s current locale and time zone. The defaultNSDateFormatterobject will already be configured for the user’s current settings.All you need to do in code is something like this:
If you print or display the string returned from here now, the example string you provided “2012-07-04T00:16:12Z” would display for me (in New York) as “2012-07-03 20:16” using the code above.
EDIT: I should note that the above code assumes an ARC environment. If you’re not using ARC, add
autoreleasemessages to the creation of the two date formatters, or they will be leaked.