发现小时之间的差异

Find different between hours

我有两个小时和分钟:

我从用户那里得到了这个时间。那你的开始时间和结束时间是多少。

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

现在我必须找到用户工作的总时间。意味着它获取 总时间:8:00

如何获取?

我正在 Objective C 中调用此代码。

我想它会对你有所帮助。

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));

这样试试!

let calendar = NSCalendar.current

    let datecomponents = calendar.dateComponents([.hour], from: start as Date, to: someDateTime as Date)
    let hours = datecomponents.hour!
    print("hours: \(hours)")

试试这个功能

-(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"]);