如何将时间与当前日期和时间进行比较?

如何将时间与当前日期和时间进行比较?

问题描述:

在我的应用程序中,我必须在给定的时间内完成一个特定的任务.所以首先我计算了完成任务的时间(以秒为单位),然后将该时间添加到像这样的当前时间.

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

现在我这样比较时间

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 ?

我有一个例子,我从选择器那里获取时间并检查是今天还是明天.您应该能够只获取代码并以您的方式使用它......

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...

int selectedHour =  [customPickerView selectedRowInComponent:0];
int selectedMinute =  [customPickerView selectedRowInComponent:1];

NSDate *today = [NSDate date];
NSDateFormatter *weekdayFormatter = [[[NSDateFormatter alloc] init]autorelease];
NSDateFormatter *hmformatter = [[[NSDateFormatter alloc] init]autorelease];
[hmformatter setDateFormat: @"hh mm"];
[weekdayFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[weekdayFormatter setDateFormat: @"EE"];
// NSString *formattedDate = [formatter stringFromDate: today];


NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
NSDateComponents *dateComponentsToday = [gregorian components:(NSHourCalendarUnit  | NSMinuteCalendarUnit | NSDayCalendarUnit) fromDate:today];


NSInteger currentHour = [dateComponentsToday hour];
NSInteger currentMinute = [dateComponentsToday minute];

NSString *weekday; 



if ((selectedHour > currentHour) | ((selectedHour == currentHour) & (selectedMinute > currentMinute))) {
    //so we are still in today
    weekday = [weekdayFormatter stringFromDate: today];
    weekday =  NSLocalizedString(@"today", @"today");
} else {
    //the timer should start tomorrow
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    NSDate *tomorrow = [today dateByAddingTimeInterval:secondsPerDay];
    weekday = [weekdayFormatter stringFromDate: tomorrow];
    weekday =  NSLocalizedString(@"tomorrow", @"tomorrow");
}