9

現在の日付を別の日付と比較したいのですが、それが現在の日付よりも前の日付である場合は、次のアクションを停止する必要があります。これどうやってするの?

今日の日付はyyyy-MM-ddフォーマットで持っています。この状態を確認する必要があります

if([displaydate text]<currentdate)
{
    //stop next action 
}

ここで、displaydateが今日の日付よりも短い場合は、その条件を入力する必要があります。

4

4 に答える 4

35
NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [dateFormatter dateWithString:@"xxxxxx"]; // your date 

NSComparisonResult result; 
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending

result = [today compare:newDate]; // comparing two dates

if(result==NSOrderedAscending)
    NSLog(@"today is less");
else if(result==NSOrderedDescending)
    NSLog(@"newDate is less");
else
    NSLog(@"Both dates are same");

この回答から解決策を得ましたObjective-Cで2つの日付を比較する方法

于 2012-11-05T09:27:59.387 に答える
1

@NNitin Gohel's答える代わりに。

NSTimeIntervalieを使用して比較しNSDate timeIntervalSince1970ます:

NSTimeInterval *todayTimeInterval = [[NSDate date] timeIntervalSince1970];
NSTimeInterval *previousTimeInterval = [previousdate timeIntervalSince1970];

if(previousTimeInterval < todayTimeInterval)
   //prevous date is less than today
else if (previousTimeInterval == todayTimeInterval)
   //both date are equal
else 
   //prevous date is greater than today
于 2012-11-05T09:31:34.957 に答える
0

NSDateFormatterに関するこのチュートリアルを詳しく見ることができます。また、NSDateオブジェクトがある場合は、それを別のNSDateと比較して、秒単位の差であるNSTimeIntervalを取得できます。

NSDate *nowDate = [NSDate date];
NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];
于 2012-11-05T09:29:12.687 に答える
0

NSDateクラスのいくつかのメソッドは次のとおりです。

  1. isEarlierThanDate。//このメソッドを使用すると、日付が前かどうかを確認できます。
  2. isLaterThanDate
  3. minutesAfterDate
  4. minutesBeforeDate。等..

iPhoneSDKのNSDateの多くのメソッドに関するこのリンクも参照してください。

How-to-real-world-dates-with-the-iphone-sdk

アップデート

//Current Date
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = nil;
    formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];

NSStringの日付をNSDate形式に変換するには、次のメソッドを使用します。このメソッドをyour.mファイルに貼り付けるだけです。

- (NSDate *)convertStringToDate:(NSString *) date {
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:@"yyyy-MM-dd"];
// NSLog(@"date============================>>>>>>>>>>>>>>> : %@", date);
date = [date stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
nowDate = [formatter dateFromString:date];
// NSLog(@"date============================>>>>>>>>>>>>>>> : %@", nowDate);
return nowDate;
}

その後、使いたいときは以下のように使ってください。

NSDate *tempDate2 = [self convertStringToDate:yourStringDate];

そして、このように比較してみてください。

if (tempDate2 > nowDate)
于 2012-11-05T09:32:09.923 に答える