1

我有两个日期选择器,它们给了我一个 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
}

谢谢

4

2 回答 2

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");
 }
于 2013-04-10T05:53:20.007 回答
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");
于 2013-04-10T04:29:52.480 回答