如何从iphone IOS上的时间间隔解析并提取年,月,日等 [英] How to parse and extract Year, Month, Day etc from time interval on iphone IOS

查看:114
本文介绍了如何从iphone IOS上的时间间隔解析并提取年,月,日等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am slowly getting into iOS development and trying to create a count up timer from a specific date. I have figured out the code which gives me the interval in seconds but I could not figure out how to extract Year/Month/Day/Hour/Minute/Second values from it in order to display each value in its own label as a ticker.

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

So far I have figured out that the following will give me the interval between the 2 dates in seconds, what I am trying to do is to parse this and display on my view this as a ticker by updating the UILabel every second using NSTimer and calling selector once every 1 seconds and get something like this on my view:

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

6Years 10Months 13Days 18Hours 25Minutes 18Seconds (obviously each label will be updated accordingly as the time goes up)

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

NSTimeInterval passed = [[NSDate date] timeIntervalSinceDate: startDate];

谢谢

推荐答案

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

Use NSCalendar with the two dates:

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

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

Returns, as an NSDateComponents object using specified components, the difference between two supplied dates.

示例:

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

NSLog输出:

13Years 10Months 6Days 8Hours 6Minutes 7Seconds

这篇关于如何从iphone IOS上的时间间隔解析并提取年,月,日等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆