Reputation: 61
I have two times :
10:23:51
10:31:54
Both values are stored as strings in a SQLite database.
I want to find the difference between these two times in hh:mm format.
How can I do this?
I have searched a lot. But can't find a proper solution. Help me out. Thanks.
Edit :
See basically I am having two arrays:
InTimeArray
and OuttimeArray
.
Now in the viewDidload
method , I am fetching all the intime
entries in the IntimeArray
and Outtime
entries in the outtime
Arrays.
Now I am passing one by one values in tableview like in 1st row
IntimeArray[0]
OuyTimeArray[0]
second row:
IntimeArray[1]
OuyTimeArray[1]
Now I want to count the differences between 1st row's intime
and outtime
in HH:MM format.
I am really confused.
Upvotes: 1
Views: 496
Reputation: 14169
Try this:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate *d1 = [formatter dateFromString:IntimeArray[0]];
NSDate *d2 = [formatter dateFromString:OuyTimeArray[0]];
NSTimeInterval ti = [d2 timeIntervalSinceDate:d1];
float hours = floor(ti / 3600);
float minutes = floor((ti - hours*3600) / 60);
NSString *s = [NSString stringWithFormat:@"%02.0f:%02.0f",hours,minutes];
For your given example, NSLog(@"Time passed: %@",s);
will print 00:08
.
Upvotes: 0
Reputation: 1545
You have to first change your both strings into date format using this method :-
- (NSDate *)dateFromString:(NSString *)string;
after that you just have to calculate number of seconds between both the dates.Thats it.
OR there is another simple way to do this. i.e.
get dates from both arrays first like this:-
NSDate *eventStartDate = [IntimeArray objectAtIndex:indexpath.row];
NSDate *eventEndDate = [OuyTimeArray objectAtIndex:indexpath.row];
Then calculate difference between both the dates like this :-
NSTimeInterval startTimeInterval = [eventStartDate timeIntervalSinceDate:currentDate];
Hope it helps Thanks :)
Upvotes: 1
Reputation: 677
you can take a look at that :
-(NSDate *)dateFromString:(NSString *)string
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormat setLocale:locale];
[dateFormat setDateFormat:@"HH:mm:ss"];
NSDate *date1 = [dateFormat dateFromString:string];
if(!date1) date1= [NSDate date];
[dateFormat release];
[locale release];
return date1;
}
this will turn the NSDate to you and when you change them both to NSDates then you can learn the difference by looking at this.
i hope this will help you..
Upvotes: 1