0

私のアプリケーションでは、特定のタスクを特定の時間内に完了する必要があります。まず、タスクを完了する時間を秒単位で計算し、その時間をこのように電流に追加します。

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

しかし、私が知りたいのは、時間が残っているかどうかです。現在の時刻が現在の時刻よりも小さいか大きいかです。

4

3 に答える 3

1

timeIntervalSinceNow は NSDate を Now と比較します。NSDate が Now より後の場合、戻り値は正になります。日付が Now より前の場合、結果は負になります。

double timeLeft = [TaskCompltTime timeIntervalSinceNow];

 if(  timeLeft > 0.0 )
 // still time left 

 else
     //time is up
于 2011-09-10T07:05:32.743 に答える
0

ええ、あなたの目的のためには、おそらく時間間隔で作業するのが最善です。Objective-CのNSTimeIntervalは、のエイリアスでdoubleあり、秒単位の時間値を表します(もちろん、少なくともミリ秒の解像度までの分数)。

NSDateには、このためのいくつかのメソッドがあり+timeIntervalSinceReferenceDateます。これは、2001年1月1日からの秒数を返します。-timeIntervalSinceReferenceDateこれは、提供されたNSDateオブジェクトと2001年1月1日との時間差-timeIntervalSinceDate:を返します。 2つのNSDateオブジェクト、および-timeIntervalSinceNow、現在の時刻とNSDateオブジェクトの差を返します。

多くの場合、代わりにNSDate値をNSTimeIntervalとして格納するのが最も便利です(たとえば、timeIntervalSinceReferenceDate)。このように、それを保持して廃棄する必要はありません。

于 2011-09-10T12:14:25.223 に答える
0

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");
}
于 2011-09-10T07:08:57.573 に答える