0

I want to get the difference between two dates which are being received in dot net format. I have converted the date into an NSDate. But I am not able to get the exact difference (the hours, minutes, and seconds fields are zero) between the dates. I am using the method below.

- (NSString*)calculateTimeFromDate :(NSDate*)date {

NSDate *createdDate;
NSDate *todayDate;


NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:SS"];

NSString *str = [formatter  stringFromDate:date];
NSString *str1= [formatter stringFromDate:[NSDate date]];


createdDate = [formatter dateFromString:str];;
todayDate = [formatter dateFromString:str1];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];


NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate:createdDate
                                              toDate:todayDate options:0];
NSInteger timeDifference = [components day];

int days = timeDifference;
NSString *timeStr;
if(days>0) {

    if(days == 1)  timeStr = [NSString stringWithFormat:@"%.0i %@",days, LString(@"DAY")];
    else           timeStr = [NSString stringWithFormat:@"%.0i %@ ",days, LString(@"DAYS")];
   } else {

    int hours = [components hour];
    if(hours >0){

        if(hours ==1)  timeStr = [NSString stringWithFormat:@"%.0i %@",hours, LString(@"HOUR")];
        else           timeStr = [NSString stringWithFormat:@"%.0i %@",hours, LString(@"HOURS")];
    } else {

        int minutes = [components minute];
        if(minutes>0) {

            if(minutes ==1 )   timeStr = [NSString stringWithFormat:@"%.0i %@",minutes, LString(@"MINUTE")];
            else               timeStr = [NSString stringWithFormat:@"%.0i %@",minutes, LString(@"MINUTES")];
        } else {

            int seconds =[components second];
            if(seconds >5)  timeStr=[NSString stringWithFormat:@"%.0i %@",seconds, LString(@"SECONDS")];
            else            timeStr = LString(@"JUST_NOW");
        }
    }
}
if(![timeStr isEqualToString:LString(@"JUST_NOW")])   timeStr = [timeStr stringByAppendingFormat:@" %@", LString(@"AGO")];
NSLog(@"%@",timeStr);
return timeStr;
}
Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
arunit21
  • 670
  • 1
  • 11
  • 25
  • 1
    In the above method *str, *str1 I have got the exact time and date but i can't get the correct date in the components. The Actual date given to me is Date(1377216000000). Please suggest ur answers... – arunit21 Aug 24 '13 at 10:26
  • -1 so the question is not about the code you have posted but about how to turn `Date(1377216000000)` into a NSDate? Maybe you should have asked that. The code you have posted works well. – Matthias Bauch Aug 24 '13 at 11:06
  • I have converted the date to nsdate format. But while nslogging the date the hours,minutes components is zero. When i set break point and hover cursor on the date object i am able to see the hours, mins,secs. What is the exact problem. – arunit21 Aug 24 '13 at 11:46

3 Answers3

3

try this: https://github.com/jonhocking/PrettyTimestamp

It's a really cool category on NSDate that returns the difference between two dates, as a nice string, like "a minute ago"

If it is not exactly what you want I'm sure it will help guide you in the right direction, or it could be modified to return the string however you like.

Sam
  • 5,892
  • 1
  • 25
  • 27
0

• Difference between two dates can be calculated by using - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

NSTimeInterval timeInterval  = [todayDate timeIntervalSinceDate:createdDate];

• Convert timeInterval into Hours, minutes and seconds.

int minutes = floor(timeInterval/60);
int seconds = trunc(timeInterval - minutes * 60);
int hours = minutes / 60;
Savitha
  • 561
  • 6
  • 19
  • It's not a good idea to use time intervals to do calculations with calendar units. If, for instance, there was a leap second, your calculations could be off. Also if you assumed 24 hours in a day, and then daylight savings ended or began, you would be an hour off. – Carl Veazey Aug 24 '13 at 11:00
0

Don't reinvent the wheel, use a library for the task.

There are several github projects out there, but this is one of the best in my opinion, FormatterKit, create and maintained by Mattt Thomposon, the author of AFNetworking.

It works great and it provides support for localization too.

Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235