如何在iphone中比较当前date和以前的date?
我想将当前date与另一个date进行比较,如果date早于当前date,那么我应该停止下一个操作。 我怎样才能做到这一点?
我有yyyy-MM-dd
格式的今天的date。 我需要检查这个情况
if([displaydate text]<currentdate) { //stop next action }
这里如果displaydate
小于今天的date,那么它必须进入该条件。
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");
从这个答案得到你的解决scheme如何比较Objective-C中的两个date
替代 @NNitin Gohel's
答案。
比较使用NSTimeInterval
即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
NSDate
类的一些方法是:
-
isEarlierThanDate
。 / /使用这种方法,你可以找出date是否过去或没有.. -
isLaterThanDate
-
minutesAfterDate
。 -
minutesBeforeDate
。 等等..
在iPhone SDK中也可以看到NSDate的很多方法。
如何对真实世界的date,用最iphone-SDK
更新
//Current Date NSDate *date = [NSDate date]; NSDateFormatter *formatter = nil; formatter=[[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd"];
使用下面的方法将NSStringdate转换为NSDate格式,只需将这个方法粘贴到你的.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; }
之后,当你想使用它只是使用像波纹pipe..
NSDate *tempDate2 = [self convertStringToDate:yourStringDate];
然后尝试像这样比较..
if (tempDate2 > nowDate)
你可以仔细看看这个关于NSDateFormatter的教程 ,当你有你的NSDate对象时,你可以将它与另一个NSDate进行比较,并得到一个NSTimeInterval,这是几秒钟内的差异。
NSDate *nowDate = [NSDate date]; NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];