如何将时间与当前日期和时间进行比较?
在我的应用程序中,我必须在给定时间内完成特定任务。因此,首先我计算完成任务的时间(以秒为单位),然后将该时间添加到当前时间,如下所示。
NSDate *mydate = [NSDate date];
NSTimeInterval TotalDuraionInSec = sec.cal_time * 60;
TaskCmpltTime = [mydate addTimeInterval:TotalDuraionInSec];
NSLog(@"task will be completed at%@",TaskCmpltTime);
现在我像这样比较时间
if([CurrentTime isEqualToDate:AfterCmpltTime]){
NSLog (@"Time Finish");
}
,但我想知道是否还剩下时间。当前时间是小于还是大于当前时间我怎么知道这一点?
In My application I have to complete a particular task in given time.So first i calculated the time complete the task in seconds and then add that time to the current that like this.
NSDate *mydate = [NSDate date];
NSTimeInterval TotalDuraionInSec = sec.cal_time * 60;
TaskCmpltTime = [mydate addTimeInterval:TotalDuraionInSec];
NSLog(@"task will be completed at%@",TaskCmpltTime);
now I compare time like this
if([CurrentTime isEqualToDate:AfterCmpltTime]){
NSLog (@"Time Finish");
}
but I want to know is Time is left or not.Is current time is less then or greater then current time how can i know this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
timeIntervalSinceNow 将 NSDate 与 Now 进行比较。如果 NSDate 晚于 Now,则返回值为正,如果日期早于 Now,则返回值为负。
timeIntervalSinceNow compares the NSDate with Now. if NSDate is after Now the return value is possitive, if the date is earlier than Now the result is negative.
我有一个例子,我从选择器中获取时间并检查是今天还是明天。您应该能够获取代码并以您的方式使用它......
I have an example where I get the time from a picker and check if its today or tomorrow. You should be able to just take the code and use it in your way...
是的,就您的目的而言,最好按时间间隔工作。 Objective-C 中的 NSTimeInterval 是 double 的别名,它表示以秒为单位的时间值(当然,还有小数,至少精确到毫秒)。
NSDate 上有几种方法可以实现此目的 -
+timeIntervalSinceReferenceDate
,它返回自 2001 年 1 月 1 日以来的秒数,-timeIntervalSinceReferenceDate
,它返回 2001 年 1 月 1 日以来的时间差提供的 NSDate 对象和 Jan 1, 2001,-timeIntervalSinceDate:
,它返回两个 NSDate 之间的秒数差异对象,以及-timeIntervalSinceNow
,它返回当前时间与 NSDate 对象之间的差异。很多时候,将 NSDate 值存储为 NSTimeInterval(例如 timeIntervalSinceReferenceDate)是最方便的。这样就不必保留和处置等。
Yeah, for your purposes it's probably best to work in time intervals. The NSTimeInterval in Objective-C is an alias for
double
, and it represents a time value in seconds (and, of course, fractions, down to at least millisecond resolution).There are several methods on NSDate for this --
+timeIntervalSinceReferenceDate
, which returns the number of seconds since Jan 1, 2001,-timeIntervalSinceReferenceDate
, which returns the difference in time between the supplied NSDate object and Jan 1, 2001,-timeIntervalSinceDate:
, which returns the difference in seconds between the two NSDate objects, and-timeIntervalSinceNow
, which returns the difference between the current time and the NSDate object.Lots of times it's most convenient to store an NSDate value as an NSTimeInterval instead (eg, timeIntervalSinceReferenceDate). This way it doesn't have to be retained and disposed, etc.