【发布时间】:2012-10-25 02:43:52
【问题描述】:
我想将当前日期与另一个日期进行比较,如果该日期早于当前日期,那么我应该停止下一步操作。我该怎么做?
我有yyyy-MM-dd 格式的今天日期。我需要检查这种情况
if([displaydate text]<currentdate)
{
//stop next action
}
这里如果displaydate 小于今天的日期,那么它必须输入那个条件。
【问题讨论】:
我想将当前日期与另一个日期进行比较,如果该日期早于当前日期,那么我应该停止下一步操作。我该怎么做?
我有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");
从这个答案How to compare two dates in Objective-C得到你的解决方案
【讨论】:
您可以仔细查看此Tutorial about NSDateFormatter,当您拥有 NSDate 对象时,您可以将其与另一个 NSDate 进行比较,并获得以秒为单位的 NSTimeInterval。
NSDate *nowDate = [NSDate date];
NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];
【讨论】:
替代@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。 // 使用这个方法你可以知道日期是不是以前的.. isLaterThanDateminutesAfterDate。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"];
使用下面的方法将 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)
【讨论】: