2013-09-28 68 views
0

我是一个新手&作为我的学习目标的一部分-c我决定想出这个简单的应用程序 - 我想显示在过去的日期&当前日期与显示的内容之间的时间不断更新,即秒&分钟等继续计数。如何显示当前日期和过去的日期之间的差异?

这是我到目前为止有:

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss '+0000'"]; 
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; 
NSDate *birthDate = [dateFormat dateFromString:@"Fri, 17 Feb 1989 13:00:00 +0000"]; 
NSDate *todaysDate = [NSDate date]; 

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSUInteger timeComponents = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit; 

NSDateComponents *comps = [gregorian components:timeComponents fromDate:birthDate toDate:todaysDate options:0]; 

NSInteger numberOfYears = [comps year]; 
NSInteger numberOfMonths = [comps month]; 
NSInteger numberOfDays = [comps day]; 
NSInteger numberOfHours = [comps hour]; 
NSInteger numberOfSeconds = [comps second]; 

NSString *yearsString = [NSString stringWithFormat:@"%ld", (long)numberOfYears]; 
_years.text = yearsString; 

NSString *monthsString = [NSString stringWithFormat:@"%ld", (long)numberOfMonths]; 
_months.text = monthsString; 

NSString *daysString = [NSString stringWithFormat:@"%ld", (long)numberOfDays]; 
_days.text = daysString; 

NSString *hoursString = [NSString stringWithFormat:@"%ld", (long)numberOfHours]; 
_hours.text = hoursString; 

NSString *secondsString = [NSString stringWithFormat:@"%ld", (long)numberOfSeconds]; 
_seconds.text = secondsString; 
} 

我有两个问题:

  1. 秒的输出显示不正确 - 秒数以千计出现像“1176” ?所有其他日期组件似乎正确显示。
  2. 输出不会更新 - 它显示一个固定的金额。我还没有真的试图设置这一点,因为我不知道实施这个的“正确”方式是什么 - 我会很感激这方面的一些指示/方向:)

回答

1
  1. 将NSMinuteCalendarUnit合并到组件标志中。
  2. viewDidLoad运行一次。如果你想连续运行这个代码,你需要在一个循环中运行它(坏)或者设置一个计时器来再次运行它(好的)。

我建议将所有与时间有关的代码移动到一个新方法中,也许称为- (void)showTime。然后,你可以创建一个定时器是这样的:

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];

存储在一个实例变量这个定时器类,所以你可以废止和零它后,当你不需要它了。

+0

不能相信我错过了分钟!回到小学我想! – user2820855

相关问题