找出不同的时间

时间:2017-04-27 10:07:14

标签: ios objective-c iphone nsdate

我有两个小时和几分钟:

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

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

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

我如何得到它?

我在目标C中使用此代码。

3 个答案:

答案 0 :(得分:0)

我认为它会对你有所帮助。

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

答案 1 :(得分:0)

试试这个!

let calendar = NSCalendar.current

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

答案 2 :(得分:0)

尝试此功能

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