-1

NOTE: I have used the share knowledge feature to answer this question as a whole and not simply one question which is commonly asked - "Splitting strings"

2 questions I have come across but never together are:

How do I split Strings? (I acknowledge this question alone has been answered a few times)

How do I calculate the difference between 2 times as strings and display in time format (00:00:00)?

The purpose of this question is to help people who are storing times are strings in core data to be able to calculate the difference between the two. I used the "share knowledge" feature to answer this question and have not simply answered. Please see below.

App Dev Guy
  • 5,396
  • 4
  • 31
  • 54
  • I understand that you are trying to make a canonical question/answer, however, the question still has to be a valid question. It is even less of a valid question after your edit. – Kevin B Oct 03 '14 at 15:32

2 Answers2

1

Since you're coming from strings, you'll need to change them to NSDate objects. You'll use a formatter to do so.

NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"HH:mm:ss"];  
// I don't know what date format you're coming from, you should of course use yours. check out the doc for more info.
NSDate *date1 = [dateFormat dateFromString:string1]; 
NSDate *date2 = [dateFormat dateFromString:string2]; 

Now you have date objects that are coming from your strings. If you want to know the time between time dates (in seconds or other)

(from this post)

 NSTimeInterval distanceBetweenDates = [date1 timeIntervalSinceDate:date2];
 double secondsInAnHour = 3600;
 NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;

NSTimeInterval gives you the difference in seconds, you can just calculate from there if you want hours, days, etc.

But sometimes, you might only need to know if a date is before or after another. Then you should use date compare, which returns a NSOrderingDesc or Asc or Same , like this:

//Then the comparison will tell which is earlier/later/same:

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
} else {
    NSLog(@"dates are the same");
}
Community
  • 1
  • 1
Gil Sand
  • 5,802
  • 5
  • 36
  • 78
0

First we establish the format of the date like so. I am using HH:MM:SS format. Format yours to suit your saved string.

NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"HH:mm:ss"];

The second part is referencing your strings. I create a new reference just to keep it tidy when converting String Date to NSDate. In my example I have declared a reference to Core Data in my .h file so I reference as follows.

NSString * StringTime1 = self.coreDataReference.time1;
NSString * StringTime2 = self.coreDataReference.time2;

Convert the strings to date:

NSDate *time1 = [dateFormat dateFromString:StringTime1];
NSDate *time2 = [dateFormat dateFromString:StringTime2];

I next get the difference by getting the time interval between the times. I am comparing the latest saved time (time2) against the first save time (time1). This method essentially subtracts whatever time is allocated second from the first, which in this case tim2 subtracts time1. You will see why in a moment.

NSTimeInterval distanceBetweenDates = [time2 timeIntervalSinceDate:time1];

For displaying purposes, I convert the time which is now a double (NSTimeInterval is a double, check https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html for more information) and then convert them into hours, minutes and second values.

int timeInt = (int) distanceBetweenDates;

//I convert the values into the time value
int hours = timeInt / 3600;
int minutes = (timeInt / 60) % 60;
int seconds = timeInt % 60;

FInally we display the results in log and if you have a label display there as well.

NSLog(@"The total time is: %02u:%02u:%02u", hours, minutes, seconds);

NSString * time = [NSString stringWithFormat:@"%02u:%02u:%02u", hours, minutes, seconds];

self.totalLoginTimeLabel.text = time;

I hope this helps anyone investigating.

The whole code here:

-(void) calculateTimeIntervalFromStrings{

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"HH:mm:ss"];

    NSString * StringTime1 = self.coreDataReference.time1;
    NSString * StringTime2 = self.coreDataReference.time2;

    NSDate *time1 = [dateFormat dateFromString:StringTime1];
    NSDate *time2 = [dateFormat dateFromString:StringTime2];

    NSTimeInterval distanceBetweenDates = [time2 timeIntervalSinceDate:time1];

    int timeInt = (int) distanceBetweenDates;

    //I convert the values into the time value
    int hours = timeInt / 3600;
    int minutes = (timeInt / 60) % 60;
    int seconds = timeInt % 60;

    NSLog(@"The total time is: %02u:%02u:%02u", hours, minutes, seconds);

    NSString * time = [NSString stringWithFormat:@"%02u:%02u:%02u", hours, minutes, seconds];

    self.timeDifferenceLabel.text = time;


}

To call this method, place in your viewDidLoad method like so:

[self calculateTimeIntervalFromStrings];
App Dev Guy
  • 5,396
  • 4
  • 31
  • 54
  • You shouldn't use so many objects/variables when you could just use NSTimeInterval which does that very specific job. – Gil Sand Oct 03 '14 at 14:26
  • Because you've answered your own question 3 seconds after you posted it. Because it's been asked many times already if you look it up. Because you're doing it wrong. – Gil Sand Oct 03 '14 at 14:33
  • I used the share your knowledge feature that is at the bottom of the "ask question" for the purpose of sharing my answer. Wasn't answered separately as a "Hey I need help but let me answer myself". Sorry for any misunderstanding. Perhaps StackExchange need to display a different colour heading or some similar feature to notify the difference between a question and sharing knowledge. – App Dev Guy Oct 03 '14 at 14:38
  • Fine, fine, sorry i've been a bit rude but this question can be answered by just asking google (or pretty much), which is what I did in less than 5 minutes (and i'm nowhere near being a good programmer). I feel like this post is more a duplicate than anything. That being said, i'll leave it as is, there is no need to talk more about this :) – Gil Sand Oct 03 '14 at 14:40