-1

I have two hours and minutes :

I got this time from user. that what is your start time and end time.

1) 10:00 AM
2) 06:00 PM

Now i have to find total time user worked for. Means it fetch total time: 8:00

How do i get it ?

I am ding this code in Objective C.

vv01f
  • 362
  • 1
  • 4
  • 21
Kavi Patel
  • 21
  • 6

3 Answers3

0

I think it will help you.

NSString *time1 = @"10.00 pm";
NSString *time2 = @"06.00 pm";
NSDate *date1;
NSDate *date2;
{
  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   [formatter setDateFormat:@"hh.mm a"];
  date1 = [formatter dateFromString:time1];
  date2 = [formatter dateFromString:time2];
  [formatter release];
}
 NSTimeInterval interval = [date1 timeIntervalSinceDate: date2]; //[date1 timeIntervalSince1970] - [date2 timeIntervalSince1970];
  int hour = interval / 3600;
 int minute = (int)interval % 3600 / 60;

NSLog(@"%@ %dh %dm", interval<0?@"-":@"+", ABS(hour), ABS(minute));
holex
  • 23,961
  • 7
  • 62
  • 76
Ramdeo angh
  • 179
  • 9
0

Try like this!

let calendar = NSCalendar.current

    let datecomponents = calendar.dateComponents([.hour], from: start as Date, to: someDateTime as Date)
    let hours = datecomponents.hour!
    print("hours: \(hours)")
Bhupat Bheda
  • 1,968
  • 1
  • 8
  • 13
0

Try this function

-(NSString *)startTime:(NSString *)startTime AndWithAndTime:(NSString *)endTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"hh:mm a"];
    NSDate *date1 = [formatter dateFromString:startTime];
    NSDate *date2 = [formatter dateFromString:endTime];
    NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
    int hours = (int)interval / 3600;             // integer division to get the hours part
    int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
    NSString *timeDiff = [NSString stringWithFormat:@"%d:%02d", hours, minutes];
    return timeDiff;
}

NSLog(@"%@",[self startTime:@"10:00 AM" AndWithAndTime:@"06:00 PM"]);
KKRocks
  • 8,222
  • 1
  • 18
  • 84