我想将当前日期与另一个日期进行比较,如果该日期早于当前日期,那么我应该停止下一个操作。我怎么能这样做?
我今天的日期是yyyy-MM-dd
格式。我需要检查这个条件
if([displaydate text]<currentdate)
{
//stop next action
}
如果displaydate
小于今天的日期,则必须输入该条件。
答案 0 :(得分:36)
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");
从这个答案中获得了解决方案How to compare two dates in Objective-C
答案 1 :(得分:1)
替代至@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
答案 2 :(得分:1)
NSDate
类的一些方法是:
isEarlierThanDate
。 //使用这种方法你可以找出以前的日期是不是.. isLaterThanDate
minutesAfterDate
。minutesBeforeDate
。等。在iPhone SDK中也可以看到许多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"];
使用此bellow方法将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)
答案 3 :(得分:0)
您可以仔细查看此Tutorial about NSDateFormatter,当您拥有NSDate对象时,可以将其与另一个NSDate进行比较,并获得NSTimeInterval,它是以秒为单位的差异。
NSDate *nowDate = [NSDate date];
NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];