72

2 つの NSDates を比較する最も効率的/推奨される方法は何ですか? 時間に関係なく、両方の日付が同じ日にあるかどうかを確認できるようにしたいと思います。NSDate クラス内で timeIntervalSinceDate: メソッドを使用し、この値の整数を秒数で割った値を取得するコードを書き始めました。一日に。これは長々としたようで、明らかな何かが欠けているように感じます。

私が修正しようとしているコードは次のとおりです。

if (!([key compare:todaysDate] == NSOrderedDescending))
{
    todaysDateSection = [eventSectionsArray count] - 1;
}

key と todaysDate は NSDate オブジェクトで、todaysDate は以下を使用して作成しています。

NSDate *todaysDate = [[NSDate alloc] init];

よろしく

デイブ

4

16 に答える 16

83

オブジェクトの「一日の始まり」の日付を取得するためのこのオプションが他にないことに驚いています。

[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay startDate:&date1 interval:NULL forDate:date1];
[[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitDay startDate:&date2 interval:NULL forDate:date2];

どちらが設定date1date2れ、それぞれの日の始まりになります。それらが等しい場合、それらは同じ日にあります。

またはこのオプション:

NSUInteger day1 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit: forDate:date1];
NSUInteger day2 = [[NSCalendar currentCalendar] ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:date2];

どちらがday1day2を比較可能な任意の値に設定します。それらが等しい場合、それらは同じ日にあります。

于 2009-12-07T02:07:11.673 に答える
73

比較を行う前に、日付の時刻を 00:00:00 に設定します。

unsigned int flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:flags fromDate:date];

NSDate* dateOnly = [calendar dateFromComponents:components];

// ... necessary cleanup

次に、日付値を比較できます。リファレンス ドキュメントの概要を参照してください。

于 2009-12-06T09:52:29.110 に答える
20

iOS 8 で NSCalendar に導入された新しいメソッドがあり、これによりこれがはるかに簡単になります。

- (NSComparisonResult)compareDate:(NSDate *)date1 toDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit NS_AVAILABLE(10_9, 8_0);

重要な単位に粒度を設定します。これにより、他のすべての単位が無視され、選択された単位との比較が制限されます。

于 2015-02-14T18:32:38.730 に答える
16

iOS8 以降では、2 つの日付が同じ日にあるかどうかを確認するのは次のように簡単です。

[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2]

ドキュメントを見る

于 2015-11-30T01:17:04.997 に答える
10

これはすべての答えの省略形です:

NSInteger interval = [[[NSCalendar currentCalendar] components: NSDayCalendarUnit
                                                                  fromDate: date1
                                                                    toDate: date2
                                                                   options: 0] day];
    if(interval<0){
       //date1<date2
    }else if (interval>0){
       //date2<date1
    }else{
       //date1=date2
    }
于 2012-10-12T20:21:53.307 に答える
6

私は Duncan C のアプローチを使用しました。彼が犯したいくつかの間違いを修正しました。

-(NSInteger) daysBetweenDate:(NSDate *)firstDate andDate:(NSDate *)secondDate { 

    NSCalendar *currentCalendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [currentCalendar components: NSDayCalendarUnit fromDate: firstDate toDate: secondDate options: 0];

    NSInteger days = [components day];

    return days;
}
于 2012-04-23T13:47:57.357 に答える
6

私はこの小さなユーティリティメソッドを使用します:

-(NSDate*)normalizedDateWithDate:(NSDate*)date
{
   NSDateComponents* components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
                                              fromDate: date];
   return [calendar_ dateFromComponents:components]; // NB calendar_ must be initialized
}

calendar_(明らかに、を含むivar という名前が必要ですNSCalendar。)

これを使用すると、次のように日付が今日かどうかを簡単に確認できます。

[[self normalizeDate:aDate] isEqualToDate:[self normalizeDate:[NSDate date]]];

([NSDate date]現在の日付と時刻を返します。)

もちろん、これは Gregory の提案と非常によく似ています。このアプローチの欠点は、多くの一時NSDateオブジェクトが作成される傾向があることです。多くの日付を処理する場合は、コンポーネントを直接比較するか、のNSDateComponents代わりにオブジェクトを操作するなど、他の方法を使用することをお勧めしますNSDates

于 2009-12-06T17:25:59.317 に答える
3

答えは、誰もが思っているよりも簡単です。NSCalendar にはメソッドがあります

components:fromDate:toDate:options

このメソッドを使用すると、任意の単位を使用して 2 つの日付の差を計算できます。

したがって、次のようなメソッドを記述します。

-(NSInteger) daysBetweenDate: (NSDate *firstDate) andDate: (NSDate *secondDate)
{
  NSCalendar *currentCalendar = [NSCalendar currentCalendar];
  NSDateComponents components* = [currentCalendar components: NSDayCalendarUnit
    fromDate: firstDate 
    toDate: secondDate
    options: 0];

  NSInteger days = [components days];
  return days;
}

上記のメソッドがゼロを返す場合、2 つの日付は同じ日です。

于 2011-11-26T20:43:14.393 に答える
1

私の解決策は、NSDateFormatter を使用した 2 つの変換でした。

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyyMMdd"];
    [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

    NSDate *today = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *todayString=[dateFormat stringFromDate:today];
    NSDate *todayWithoutHour=[dateFormat dateFromString:todayString];

    if ([today compare:exprDate] == NSOrderedDescending)
    {
       //do  
    }
于 2016-02-10T16:18:28.863 に答える
1
int interval = (int)[firstTime timeIntervalSinceDate:secondTime]/(60*60*24);
if (interval!=0){
   //not the same day;
}
于 2014-09-18T09:46:04.877 に答える
0

NSDateに関するドキュメントでは、メソッドcompare:isEqual:メソッドの両方が基本的な比較を実行し、結果を順序付けますが、時間は考慮されます。

isTodayおそらく、タスクを管理する最も簡単な方法は、次の効果を持つ新しいメソッドを作成することです。

- (bool)isToday:(NSDate *)otherDate
{
    currentTime = [however current time is retrieved]; // Pardon the bit of pseudo-code

    if (currentTime < [otherDate timeIntervalSinceNow])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
于 2009-12-06T09:58:16.587 に答える
0

これは特に皮膚に醜い猫ですが、これを行う別の方法があります. 洗練されているとは言えませんが、おそらく iOS の日付/時刻のサポートに最も近いものです。

bool isToday = [[NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterNoStyle] isEqualToString:[NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterFullStyle timeStyle:NSDateFormatterNoStyle]];
于 2013-06-30T01:09:41.933 に答える
0
NSUInteger unit = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit;
NSDateComponents *comp = [cal components:unit
                                fromDate:nowDate
                                  toDate:setDate
                                 options:0];

NSString *dMonth;
dMonth = [NSString stringWithFormat:@"%02ld",comp.month];
NSString *dDay;
dDay = [NSString stringWithFormat:@"%02ld",comp.day + (comp.hour > 0 ? 1 : 0)];

時間も比較して、1日の違いを修正します

于 2015-02-27T06:06:31.627 に答える