0

I am new in iOS programming and i want to get difference between two NSDate objects but i am not able to calculate correct difference as i am not getting correct date from [NSDate Date].

Have a look at attached screenshot. I am not getting what i am doing wrong?

enter image description here

I have tried solutions from this one and this one also.

Please suggest if I am doing anything wrong?

Community
  • 1
  • 1
Akshay Sunderwani
  • 12,428
  • 8
  • 29
  • 52
  • The reason why neither of those suggestions worked for you is because you are trying to format the date **BEFORE** you work out the interval. Get the interval first and then format the date. – App Dev Guy Feb 20 '15 at 05:39
  • @SASmith Check the screenshot, my question was that i am getting wrong data "2015-19-20" and thats not possible so it was not working but now i got it and it is working. – Akshay Sunderwani Feb 20 '15 at 05:42
  • Your screen shot is about formatting not about the difference. It is a little misleading as your question is asking about how to get a time interval and not how to display it. `[NSDate date];` will give you the time right at the moment it is called and not a time difference. – App Dev Guy Feb 20 '15 at 05:44
  • @SASmith yes you are right that [NSDate Date] return current time as you are seeing log it not giving correct value and that was my question "i want to get difference between two NSDate objects but i am not able to calculate correct difference as **i am not getting correct date** from `[NSDate Date]`" – Akshay Sunderwani Feb 20 '15 at 05:51
  • 1
    I would consider renaming the question to be something about formatting the difference and not about getting the difference to avoid administrator privileged people closing it or flagging it as a duplicate :-) I hope you have solved your issue now :-) – App Dev Guy Feb 20 '15 at 05:53

3 Answers3

1

Try

const NSTimeInterval difference = [date1 timeIntervalSinceDate:date2];

This returns the number of seconds between both dates

SomeGuy
  • 9,670
  • 3
  • 32
  • 35
0

Try this,This will help you to get the difference seperately:-

unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *conversionInfo = [currCalendar components:unitFlags fromDate:fistDate   toDate:secondDate  options:0];

int months = [conversionInfo month];
int days = [conversionInfo day];
int hours = [conversionInfo hour];
int minutes = [conversionInfo minute];

[NSString stringWithFormat:@"%d months , %d days, %d hours, %d min", months, days, hours, minutes];
Mohd Prophet
  • 1,511
  • 10
  • 17
0

I got the solution for this itself only needed to replace

[formatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"]; with [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

and it worked.

Akshay Sunderwani
  • 12,428
  • 8
  • 29
  • 52