我有两个日期,比如currentdate和getDate,我想比较getdate是旧的还是新的或者相等。
我试过这个作为你的参考:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSString *currentDate = [dateFormatter stringFromDate:today];
// Current_date (7/26/2013)
NSString *getdate=[outDateformatter1 stringFromDate:bDt1];
// Get_date (7/26/2010)
NSComparisonResult result;
result = [currentDate compare:getdate]; // comparing two dates
if(result==NSOrderedAscending)
NSLog(@"today is less");
I need this, Original result getdate is old date.
但它不能正常工作,请任何人建议我这样做。
先谢谢
答案 0 :(得分:0)
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *serDate;
NSDate *endDate;
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
serDate = [formatter dateFromString:@"2012-12-07 7:17:58"];
endDate = [formatter dateFromString:@"2012-12-07 08:43:30"];
NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:serDate];
double minutes = timeDifference / 60;
double hours = minutes / 60;
double seconds = timeDifference;
double days = minutes / 1440;
NSLog(@" days = %.0f,hours = %.2f, minutes = %.0f,seconds = %.0f", days, hours, minutes, seconds);
if (hours > 1.30)
return 1;
else
return 0;
答案 1 :(得分:0)
使用compare
方法。
if ([currentdate compare: getDate] == NSOrderedDescending) {
NSLog(@"currentdate is later than getDate");
} else if ([currentdate compare:getDate] == NSOrderedAscending) {
NSLog(@"currentdate is earlier than getDate");
} else {
NSLog(@"dates are the same");
}
答案 2 :(得分:0)
//Use this function to compare current date to another date
- (NSInteger)numberOfDaysUntil:(NSDate *)aDate {
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:aDate options:0];
//NSLog(@"Number of days >>>%d",[components day]);
return [components day];
// then use this logic
if ([self numberOfDaysUntil:date]==0)
{
NSLog(@"Today");
}
else if ([self numberOfDaysUntil:date]== -1)
{
NSLog(@"Yesterday");
}
else{
// if return is -2 then date is two date before current date .
// if return is 1 then date is one future date than current day
}
答案 3 :(得分:0)
for that you have to import NSDate-Utilities.h and .m file.
NSDateFormatter * df = [[NSDateFormatter alloc] init]; [df setDateFormat:@“MM / dd / yyyy”];
float oldDate = [[df dateFromString:[dic valueForKey:@"end_date"]] timeIntervalSinceNow];
if (oldDate < 0) {
//past date
}
else if (oldDate > 0){
//future date
}
else{
//same date
}