如何从iphone IOS上的时间间隔解析并提取年,月,日等

03U*_*Usr 3 iphone nsdate nstimer ipad ios

我正在慢慢进入iOS开发并尝试从特定日期创建计数计时器.我已经找到了代码,它给出了我以秒为单位的间隔,但我无法弄清楚如何从中提取年/月/日/小时/分/秒值,以便将自己标签中的每个值显示为自动收报机.

到目前为止,我已经发现以下内容将给出两个日期之间的间隔,以秒为单位,我要做的是解析这个并在我的视图中显示这个作为自动收报机,通过使用NSTimer每秒更新UILabel并调用每1秒选择一次并在我的视图中得到类似的东西:

6年10个月13天18小时25分钟18秒(显然每个标签会随着时间的推移而相应更新)

NSDate *startDate = [df dateFromString:@"2005-01-01"];

NSTimeInterval passed = [[NSDate date] timeIntervalSinceDate: startDate];
Run Code Online (Sandbox Code Playgroud)

谢谢

zap*_*aph 10

将NSCalendar与两个日期一起使用:

- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts
Run Code Online (Sandbox Code Playgroud)

作为使用指定组件的NSDateComponents对象返回两个提供日期之间的差异.

例:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSDate *startingDate = [dateFormatter dateFromString:@"2005-01-01"];
NSDate *endingDate = [NSDate date];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];

NSInteger days     = [dateComponents day];
NSInteger months   = [dateComponents month];
NSInteger years    = [dateComponents year];
NSInteger hours    = [dateComponents hour];
NSInteger minutes  = [dateComponents minute];
NSInteger seconds  = [dateComponents second];
NSLog(@"%dYears %dMonths %dDays %dHours %dMinutes %dSeconds", days, months, years, hours, minutes, seconds);
Run Code Online (Sandbox Code Playgroud)

NSLog输出:

13Years 10Months 6Days 8Hours 6Minutes 7Seconds
Run Code Online (Sandbox Code Playgroud)