如何在iPhone上将NSTimeInterval分解为年,月,日,时,分,秒?

我有一个时间跨度多年,我希望所有的时间组件从一年下降到秒。

我的第一个想法是整数除以一秒钟的时间间隔在一年内,从运行的总秒数中减去,在一个月内除以秒,从运行总和减去,以此类推。

这看起来很复杂,我读过,当你做一些看起来很复杂的事情时,可能有一个内置的方法。

在那儿?

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

当我把dateselect器设置为过去1年和1天的date时,我得到:

1年1个月1天16小时0分20秒

这是1个月和16个小时。 如果我过去把dateselect器设置为1天,那么我的数量是相同的。

更新 :我有一个应用程序,计算你的年龄在给定你的生日(从UIDatePicker设置),但它经常closures。 这certificate有一个不准确的地方,但是我不知道它是从哪里来的,对吗?

简要描述;简介

  1. 只是另一种方法来完成JBRWilkinson的答案,但增加了一些代码。 它也可以为Alex Reynolds的评论提供一个解决scheme。

  2. 使用NSCalendar方法:

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

    • “作为使用指定组件的NSDateComponents对象返回两个提供的date之间的差异”。 (从API文档)。

  3. 创build2个NSDate,它们的区别是您想分解的NSTimeInterval。 (如果您的NSTimeInterval来自比较2 NSDate,则不需要执行此步骤,而且甚至不需要NSTimeInterval,只需将date应用于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]); 

使用+dateWithIntervalSince1970将间隔转换为NSDate使用+dateWithIntervalSince1970获取date组件。

SDK参考

这适用于我:

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

这里的主要区别是你需要调整时区。

或者有我的class级方法。 它不能处理多年,但可以很容易地添加,但对于像日,小时和分钟这样的小时间段来说更好。 它考虑到复数,只显示需要什么:

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

从iOS8和以上,你可以使用NSDateComponentsFormatter

它有方法来转换用户友好格式化string的时差。

 NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init]; formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull; NSLog(@"%@", [formatter stringFromTimeInterval:1623452]); 

这给出了输出 – 2周,4天,18小时,57分钟,32秒

 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. ... 

这是另一个可能性,更清洁:

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