iPhone에서 nstimeinterval을 1 년, 달, 며칠, 시간, 몇 분 및 몇 초로 분해하려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/1237778

문제

나는 몇 년에 걸쳐 시간 간격을 가지고 있으며 연도에서 몇 초까지 모든 시간 구성 요소를 원합니다.

나의 첫 번째 생각은 정수 시간 간격을 1 년 만에 몇 초로 나누고, 총 초의 총 초에서 한 달에 몇 초로 나누고, 달리기 총계에서 그것을 빼는 것입니다.

그것은 단지 복잡한 것처럼 보이며, 당신이 복잡해 보이는 일을 할 때마다 아마도 내장 방법이있을 것입니다.

거기가 있습니까?

Alex의 두 번째 방법을 내 코드에 통합했습니다.

그것은 내 인터페이스에서 uidatepicker가 불리는 메소드에 있습니다.

NSDate *now = [NSDate date];
NSDate *then = self.datePicker.date;
NSTimeInterval howLong = [now timeIntervalSinceDate:then];

NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong];
NSString *dateStr = [date description];
const char *dateStrPtr = [dateStr UTF8String];
int year, month, day, hour, minute, sec;

sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &sec);
year -= 1970;

NSLog(@"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds", year, month, day, hour, minute, sec);

날짜 선택기를 과거 1 년 1 일 날짜로 설정하면 다음을 얻습니다.

1 년 1 개월 1 일 16 시간 0 분 20 초

1 개월 16 시간입니다. 과거에 날짜 선택기를 1 일로 설정하면 같은 금액으로 꺼져 있습니다.

업데이트: 나는 당신의 생일을 감안할 때 (uidatepicker에서 설정) 나이를 계산하는 앱을 가지고 있지만 종종 꺼졌습니다. 이것은 부정확성이 있음을 증명하지만 어디에서 왔는지 알 수 없습니다.

도움이 되었습니까?

해결책

간단한 설명

  1. JBRWILKINSON의 답변을 완성하는 또 다른 접근 방식은 코드를 추가합니다. 또한 Alex Reynolds의 의견에 대한 솔루션을 제공 할 수 있습니다.

  2. nscalendar 방법 사용 :

    • (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts

    • "지정된 구성 요소를 사용하여 NSDATECOMPONENTS 객체로서 두 개의 제공된 날짜의 차이로 반환됩니다." (API 문서에서).

  3. 차이가있는 2 nsdate를 만들고 싶어요. (NSTIMEINTERVAL이 2 NSDATE를 비교 한 경우이 단계를 수행 할 필요가 없으며 NSTIMEINTERVAL이 필요하지 않으며 날짜를 NSCALENDAR 메소드에 적용하십시오).

  4. NSDATECOMPONENTS에서 인용문을 받으십시오

샘플 코드

// The time interval 
NSTimeInterval theTimeInterval = ...;

// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];

// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1]; 

// Get conversion to months, days, hours, minutes
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;

NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];
NSLog(@"Break down: %i min : %i hours : %i days : %i months", [breakdownInfo minute], [breakdownInfo hour], [breakdownInfo day], [breakdownInfo month]);

다른 팁

이 코드는 하루 가벼운 절약 시간과 기타 불쾌한 것들을 알고 있습니다.

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components: (NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit )
                                                    fromDate:startDate
                                                      toDate:[NSDate date]
                                                     options:0];


NSLog(@"%ld", [components year]);
NSLog(@"%ld", [components month]);
NSLog(@"%ld", [components day]);
NSLog(@"%ld", [components hour]);
NSLog(@"%ld", [components minute]);
NSLog(@"%ld", [components second]);

간격을 NSDate 사용 +dateWithIntervalSince1970, 해당 사용에서 날짜 구성 요소를 가져옵니다 NSCalendar'에스 -componentsFromDate 방법.

SDK 참조

iOS8 이상에서 사용할 수 있습니다 NSDateComponentsFormatter

사용자 친화적 인 형식의 문자열에서 시차를 변환하는 방법이 있습니다.

NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;

NSLog(@"%@", [formatter stringFromTimeInterval:1623452]);

이것은 출력 - 2 주, 4 일, 18 시간, 57 분, 32 초를 제공합니다.

이것은 나를 위해 작동합니다 :

    float *lenghInSeconds = 2345.234513;
    NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:lenghInSeconds];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];


    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];

    [formatter setDateFormat:@"HH:mm:ss"];
    NSLog(@"%@", [formatter stringFromDate:date]); 
    [formatter release];

여기서 주요 차이점은 시간대를 조정해야한다는 것입니다.

또는 내 수업 방법이 있습니다. 몇 년을 다루지는 않지만 며칠, 몇 시간 및 분과 같은 작은 타임 랩에는 더 좋습니다. 복수를 고려하고 필요한 것을 보여줍니다.

+(NSString *)TimeRemainingUntilDate:(NSDate *)date {

    NSTimeInterval interval = [date timeIntervalSinceNow];
    NSString * timeRemaining = nil;

    if (interval > 0) {

        div_t d = div(interval, 86400);
        int day = d.quot;
        div_t h = div(d.rem, 3600);
        int hour = h.quot;
        div_t m = div(h.rem, 60);
        int min = m.quot;

        NSString * nbday = nil;
        if(day > 1)
            nbday = @"days";
        else if(day == 1)
            nbday = @"day";
        else
            nbday = @"";
        NSString * nbhour = nil;
        if(hour > 1)
            nbhour = @"hours";
        else if (hour == 1)
            nbhour = @"hour";
        else
            nbhour = @"";
        NSString * nbmin = nil;
        if(min > 1)
            nbmin = @"mins";
        else
            nbmin = @"min";

        timeRemaining = [NSString stringWithFormat:@"%@%@ %@%@ %@%@",day ? [NSNumber numberWithInt:day] : @"",nbday,hour ? [NSNumber numberWithInt:hour] : @"",nbhour,min ? [NSNumber numberWithInt:min] : @"00",nbmin];
    }
    else
        timeRemaining = @"Over";

    return timeRemaining;
}
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];

// format: YYYY-MM-DD HH:MM:SS ±HHMM
NSString *dateStr = [date description];
NSRange range;

// year
range.location = 0;
range.length = 4;
NSString *yearStr = [dateStr substringWithRange:range];
int year = [yearStr intValue] - 1970;

// month
range.location = 5;
range.length = 2;
NSString *monthStr = [dateStr substringWithRange:range];
int month = [monthStr intValue];

// day, etc.
...
- (NSString *)convertTimeFromSeconds:(NSString *)seconds {

    // Return variable.
    NSString *result = @"";

    // Int variables for calculation.
    int secs = [seconds intValue];
    int tempHour    = 0;
    int tempMinute  = 0;
    int tempSecond  = 0;

    NSString *hour      = @"";
    NSString *minute    = @"";
    NSString *second    = @"";

    // Convert the seconds to hours, minutes and seconds.
    tempHour    = secs / 3600;
    tempMinute  = secs / 60 - tempHour * 60;
    tempSecond  = secs - (tempHour * 3600 + tempMinute * 60);

    hour    = [[NSNumber numberWithInt:tempHour] stringValue];
    minute  = [[NSNumber numberWithInt:tempMinute] stringValue];
    second  = [[NSNumber numberWithInt:tempSecond] stringValue];

    // Make time look like 00:00:00 and not 0:0:0
    if (tempHour < 10) {
        hour = [@"0" stringByAppendingString:hour];
    } 

    if (tempMinute < 10) {
        minute = [@"0" stringByAppendingString:minute];
    }

    if (tempSecond < 10) {
        second = [@"0" stringByAppendingString:second];
    }

    if (tempHour == 0) {

        NSLog(@"Result of Time Conversion: %@:%@", minute, second);
        result = [NSString stringWithFormat:@"%@:%@", minute, second];

    } else {

        NSLog(@"Result of Time Conversion: %@:%@:%@", hour, minute, second); 
        result = [NSString stringWithFormat:@"%@:%@:%@",hour, minute, second];

    }

    return result;

}

다음은 또 다른 가능성이 있습니다.

NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSString *dateStr = [date description];
const char *dateStrPtr = [dateStr UTF8String];

// format: YYYY-MM-DD HH:MM:SS ±HHMM
int year, month, day, hour, minutes, seconds;
sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minutes, &seconds);
year -= 1970;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top