isEqualToDate と NSDateFommatter

NSDate型に、時間が同じかどうかを判定するメソッドがある。
(BOOL)isEqualToDate:(NSDate *)anotherDate
しかし、当然のことながら、1秒でも数値が異なると、日付判定が異なってしまう。なので、NSString型で比較。

[c]
NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
[fmt setDateFormat:@"yyyy/MM/dd"];
NSString *currentDate = [fmt stringFromDate:[NSDate date]];
NSString *tommorowDate = [fmt stringFromDate:[NSDate dateWithTimeIntervalSinceNow:60*60*8]];

NSLog(@"現在:%@", currentDate);
NSLog(@"明日:%@", tommorowDate);

if ([currentDate isEqualToString: tommorowDate]) {
NSLog(@"同日です。");
}else{
NSLog(@"同日ではありません。");
}

[/c]

ちなみに、NSString型同士で、== で比較すると falseとなります。
[c]
if (currentDate == tommorowDate) {
NSLog(@"同日です。%@", result);
}else{
NSLog(@"同日ではありません。%@", result);
}
[/c]

This entry was posted in Objective-C, 技術情報. Bookmark the permalink.

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です