<分区>
我想要进行时间计算,但不知道要使用什么类,我应该使用 NSDate
吗?
我希望用户输入他每天应该上类的时间,应用程序会向他显示他的平均迟到/早到时间(以分钟为单位)。
更好的解释: 当用户第一次启动应用程序时,应用程序会询问他何时应该上类以及何时应该离开。该应用程序跟踪用户到达/离开的时间(使用工作地址和地理围栏)并计算用户上类的平均迟到和早到时间。当用户打开应用程序时,他会看到两个标签,一个表示“平均迟到”,一个表示“平均早到”。
我应该使用 NSDate
还是有更好的方法?
最佳答案
如果您只是比较持续时间,NSTimeInterval
是适合您的类型(它实际上是 float
毫秒数,向读者解释其意图)。
NSDate
对于需要以实际时钟时间开始或结束的计算是必需的。
编辑 根据描述的更具体的问题:给定用户的日常工作开始时间,计算与到达工作时间的偏差,关键计算涉及 NSDate
.
它旨在回答以下问题:与实际时钟相比,用户现在是否准时?此计算的关键参数是当前时间 NSDate
以及用户计划到达时间NSDate
可以保存为简单标量并通过 NSDateComponents
转换为 NSDate ...
// core location triggered an arrival notification and we call this
// assumes a "User" class that knows user state, like the time user is due at work
-(void)userJustArrived:(User *)myUser {
NSDate *now = [NSDate date];
NSDate *dueAtWork = [myUser dueAtWork];
NSTimeInterval lateness = [now timeIntervalSinceDate:dueAtWork];
// a negative lateness means user is early
if (lateness > 0)
NSLog(@"you are %f milliseconds late. perhaps you should go into standup comedy", lateness);
}
// on the user class, due at work produces an NSDate from what you would
// have stored earlier as the time when a user is expected at work
- (NSDate *)dueAtWork {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[NSDate date]];
// these are given as user state, the user's planned start time
components.hour = self.dueAtWorkHour;
components.minute = self.dueAtWorkMinute;
return [components date];
}
关于ios - 我应该使用 NSDate 来跟踪到达时间和迟到时间吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36102793/