测试NSDate比较的最佳方法是什么?

时间:2013-04-09 23:25:28

标签: ios objective-c cocoa-touch nsdate

我有两个日期选择器,它给了我一个startTime和一个endTime。根据这段代码:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
dateFormatter.timeZone=[NSTimeZone defaultTimeZone];
dateFormatter.timeStyle=NSDateFormatterShortStyle;
dateFormatter.dateStyle=NSDateFormatterShortStyle;
NSString *dateTimeString=[dateFormatter stringFromDate:startTime.date];
NSLog(@"Start time is %@",dateTimeString);


NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
dateFormatter2.timeZone=[NSTimeZone defaultTimeZone];
dateFormatter2.timeStyle=NSDateFormatterShortStyle;
dateFormatter2.dateStyle=NSDateFormatterShortStyle;
NSString *dateTimeString2=[dateFormatter2 stringFromDate:endTime.date];
NSLog(@"End time is %@",dateTimeString2);

在我的.h

@property (weak, nonatomic) IBOutlet UIDatePicker *startTime;
@property (weak, nonatomic) IBOutlet UIDatePicker *endTime;

我有这个代码让我在给定时间和当前时间之间进行比较。测试它的最佳方法是什么,因为我需要你在后台使用它。

if ([[NSDate date] isEqualToDate:startTime.date]) {
NSLog(@"currentDate is equal to startTime"); 
}

if ([[NSDate date] isEqualToDate:endTime.date]) {
NSLog(@"currentDate is equal to endTime"); 
}

我需要在该代码或此代码之间进行选择。那么NSLog会在这里运作吗?

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate


if([startTime.date timeIntervalSinceDate:[NSDate date]] > 0)
{
//start time greater than today
}

else if([startTime.date timeIntervalSinceDate:[NSDate date]] < 0)
{
//start time less than today
}

else
{
//both dates are equal
}

由于

2 个答案:

答案 0 :(得分:6)

NSDate *date1;
NSDate *date2;

然后,下面的比较将告诉哪个更早/更晚/相同:

 if ([date1 compare:date2] == NSOrderedDescending) {
 NSLog(@"date1 is later than date2");        

 } else if ([date1 compare:date2] == NSOrderedAscending) {
  NSLog(@"date1 is earlier than date2");

 } else {
NSLog(@"dates are the same");
 }

答案 1 :(得分:1)

您可以使用NSComparator比较两个对象值

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSDate *strDate;
NSDate *endDate;
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
strDate = [formatter dateFromString:@"2012-12-07 08:43:31"];
endDate = [formatter dateFromString:@"2012-12-07 08:43:30"];

NSLog(@"%d",[strDate compare:endDate]);
if([strDate compare:endDate] < 0)
    NSLog(@"Enddate bigger than serdate");
else if([strDate compare:endDate] > 0)
    NSLog(@"strdate bigger than enddate");
else
    NSLog(@"Both Are Identicle");