Подтвердить что ты не робот

Как рассчитать время в часах между двумя датами в iOS

Как рассчитать время, прошедшее через два часа (возможно, в разные дни) в iOS?

4b9b3361

Ответ 1

Функция NSDate timeIntervalSinceDate: даст вам разницу в две даты в секундах.

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

См. справочную библиотеку apple http://developer.apple.com/library/mac/navigation/ или если вы используете Xcode, просто выберите help/documentation в меню.

Смотрите: how-to-convert-an-nstimeinterval-seconds-into-minutes

- edit: см. ниже ÐąrέÐέvil для правильной обработки летнего времени/секунд прыжка

Ответ 2

NSCalendar *c = [NSCalendar currentCalendar];
NSDate *d1 = [NSDate date];
NSDate *d2 = [NSDate dateWithTimeIntervalSince1970:1340323201];//2012-06-22
NSDateComponents *components = [c components:NSHourCalendarUnit fromDate:d2 toDate:d1 options:0];
NSInteger diff = components.minute;

NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit

Измените необходимые компоненты на день, час или минуту, какую разницу вы хотите. Если выбрано NSDayCalendarUnit, то оно вернет число дней между двумя датами аналогично для NSHourCalendarUnit и NSMinuteCalendarUnit

Ответ 3

-(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;
}

Ответ 4

Оформить заказ: он берет на себя переход на летнее время, високосный год, поскольку он использовал календарь iOS для расчета. Вы можете изменить строку и условия, включая минуты и часы.

+(NSString*)remaningTime:(NSDate*)startDate endDate:(NSDate*)endDate {

    NSDateComponents *components;
    NSInteger days;
    NSInteger hour;
    NSInteger minutes;
    NSString *durationString;

    components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute
                                                 fromDate: startDate toDate: endDate options: 0];
    days = [components day];
    hour = [components hour];
    minutes = [components minute];

    if (days > 0) {

        if (days > 1) {
            durationString = [NSString stringWithFormat:@"%d days", days];
        }
        else {
            durationString = [NSString stringWithFormat:@"%d day", days];
        }
        return durationString;
    }

    if (hour > 0) {

        if (hour > 1) {
            durationString = [NSString stringWithFormat:@"%d hours", hour];
        }
        else {
            durationString = [NSString stringWithFormat:@"%d hour", hour];
        }
        return durationString;
    }

    if (minutes > 0) {

        if (minutes > 1) {
            durationString = [NSString stringWithFormat:@"%d minutes", minutes];
        }
        else {
            durationString = [NSString stringWithFormat:@"%d minute", minutes];
        }
        return durationString;
    }

    return @"";
}

Ответ 5

Быстрый способ

class func hoursBetweenDates(date1: NSDate, date2: NSDate) -> Int {
    let secondsBetween = abs(Int(date1.timeIntervalSinceDate(date2)))
    let secondsInHour = 3600

    return secondsBetween / secondsInHour
}