How to calculate time in hours between two dates in iOS

后端 未结 5 1152
野性不改
野性不改 2020-11-29 19:24

How can I calculate the time elapsed in hours between two times (possibly occurring on different days) in iOS?

5条回答
  •  生来不讨喜
    2020-11-29 19:49

    -(NSMutableString*) timeLeftSinceDate: (NSDate *) dateT {
    
        NSMutableString *timeLeft = [[NSMutableString alloc]init];
    
        NSDate *today10am =[NSDate date];
    
        NSInteger seconds = [today10am timeIntervalSinceDate:dateT];
    
        NSInteger days = (int) (floor(seconds / (3600 * 24)));
        if(days) seconds -= days * 3600 * 24;
    
        NSInteger hours = (int) (floor(seconds / 3600));
        if(hours) seconds -= hours * 3600;
    
        NSInteger minutes = (int) (floor(seconds / 60));
        if(minutes) seconds -= minutes * 60;
    
        if(days) {
            [timeLeft appendString:[NSString stringWithFormat:@"%ld Days", (long)days*-1]];
        }
    
        if(hours) {
            [timeLeft appendString:[NSString stringWithFormat: @"%ld H", (long)hours*-1]];
        }
    
        if(minutes) {
            [timeLeft appendString: [NSString stringWithFormat: @"%ld M",(long)minutes*-1]];
        }
    
        if(seconds) {
            [timeLeft appendString:[NSString stringWithFormat: @"%lds", (long)seconds*-1]];
        }
    
        return timeLeft;
    }
    

提交回复
热议问题