我是一个新手,作为我学习目标的一部分-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;
}
我有两个问题:
- 秒的输出显示不正确 - 秒数显示为数千,如“1176”?所有其他日期组件似乎都正确显示。
- 输出不会更新 - 它显示固定数量。我还没有真正尝试过设置它,因为我不确定实现它的“正确”方法是什么——我会很感激对此的一些指示/方向:)