現在の日付を別の日付と比較したいのですが、それが現在の日付よりも前の日付である場合は、次のアクションを停止する必要があります。これどうやってするの?
今日の日付はyyyy-MM-dd
フォーマットで持っています。この状態を確認する必要があります
if([displaydate text]<currentdate)
{
//stop next action
}
ここで、displaydate
が今日の日付よりも短い場合は、その条件を入力する必要があります。
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つの日付を比較する方法
@NNitin Gohel's
答える代わりに。
NSTimeInterval
ieを使用して比較し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
NSDateFormatterに関するこのチュートリアルを詳しく見ることができます。また、NSDateオブジェクトがある場合は、それを別のNSDateと比較して、秒単位の差であるNSTimeIntervalを取得できます。
NSDate *nowDate = [NSDate date];
NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];
NSDate
クラスのいくつかのメソッドは次のとおりです。
isEarlierThanDate
。//このメソッドを使用すると、日付が前かどうかを確認できます。isLaterThanDate
minutesAfterDate
。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)