1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NSDateとDate 比較方法の違い

Last updated at Posted at 2019-08-15

はじめに

Objective-CからSwiftへの変換で、日付の比較方法が新しくなっていたのでその覚書です。

Objective-Cでは時刻を比較するのに、NSDateのcompare:を使用し、実行結果であるNSComparisonResultを調べます。
ただこの方法は、昇順(Ascending)、降順(Descending)という名前で新旧を判断しなくてはならないため、結果を直感的に判断できませんでした(私には💦)。

しかしSwiftでは、Dateクラスを不等号で比較することが可能になったため、直感的に比較できます。

比較方法

Swift (Date)

func compare(dateA: Date, dateB: Date) {    
    // 数が大きいほうが新しい時刻
    if dateA > dateB {
        print("DateA is newer!")
    } else if dateA == dateB {
        print("Same")
    } else if dateA < dateB {
        print("DateA is older.")
    }
}

Objective-C (NSDate)

+ (void)compare:(NSDate *)dateA dateB:(NSDate *)dateB {    
    NSComparisonResult result = [dateA compare:dateB];
    switch (result) {
        case NSOrderedAscending:
            // 昇順(dateA < dateB) dateAのほうが古い
            NSLog(@"dateA is older");
            break;
            
        case NSOrderedSame:
            // 同じ
            NSLog(@"Same");
            break;
            
        case NSOrderedDescending:
            // 降順(dateA > dateB) dateAのほうが新しい
            NSLog(@"dateA is newer!");
            break;
        default:
            break;
    }
}

参照

Swift3で日付(Date)の比較が超簡単になっていた件 - Qiita
日付の比較 - Qiita

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?