如何获得两个日期之间的差异?

问题描述:

我有两种格式的日期(MM/dd/yyyy hh:mm:ss:SS)。对于这两个日期我已经通过使用(stringFromDate)方法将两个日期转换为字符串。但我无法区分它们并在控制台中显示它们。请给我一个想法,我应该如何得到它? 谢谢。如何获得两个日期之间的差异?

NSDate *today = [NSDate date]; 

NSTimeInterval dateTime; 


if ([visitDate isEqualToDate:today]) //visitDate is a NSDate 

{ 

NSLog (@"Dates are equal"); 

} 

dateTime = ([visitDate timeIntervalSinceDate:today]/86400); 

if(dateTime < 0) //Check if visit date is a past date, dateTime returns - val 

{ 

NSLog (@"Past Date"); 

} 

else 

{ 
NSLog (@"Future Date"); 

} 
+0

我建议把那幻数(86400),在这样的常量:'常量CGFloat的kSecondsPerDay = 60 * 60 * 24;'.. – zekel 2011-04-19 21:19:56

一般来说,我看到通过转换日/年的值到扁平天处理天增量计算(通常天因为一些起始epoch,像01/01/1970)。

为了解决这个问题,我发现创建一个每月开始的一年的表格是很有帮助的。最近我用这个课程。

namespace { 
    // Helper class for figuring out things like day of year 
    class month_database { 
    public: 
     month_database() { 

      days_into_year[0] = 0; 
      for (int i=0; i<11; i++) { 
       days_into_year[i+1] = days_into_year[i] + days_in_month[i]; 
      } 
     }; 

     // Return the start day of the year for the given month (January = month 1). 
     int start_day (int month, int year) const { 

      // Account for leap years. Actually, this doesn't get the year 1900 or 2100 right, 
      // but should be good enough for a while. 
      if ((year % 4) == 0 && month > 2) { 
       return days_into_year[month-1] + 1; 
      } else { 
       return days_into_year[month-1]; 
      } 
     } 
    private: 
     static int const days_in_month[12]; 

     // # of days into the year the previous month ends 
     int days_into_year[12]; 
    }; 
    // 30 days has September, April, June, and November... 
    int const month_database::days_in_month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 

    month_database month; 
} 

你可以从start_day方法看,你会与摔跤的主要问题是很多的飞跃天是如何包含在你的范围内。在我们的时代,我使用的计算已经足够好了。包含闰日的实际规则是discussed here

在公历

2月29日, 当今使用最广泛的,是一个日期 只发生每四年 年一次,在年被4整除, 如1976年,1996年,2000年,2004年,2008年, 2012年或2016年(除了 世纪年不能被400, ,如1900年整除)。

保留日期作为日期,获取它们之间的差异,然后打印差异。

docs on NSCalendar并假设阳历是NSCalendar:

NSDate *startDate = ...; 

NSDate *endDate = ...; 

unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; 

NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0]; 

int months = [comps month]; 

int days = [comps day]; 

如果你只是想在天的差别,你可以做到这一点。 (上米希尔·梅塔的答案为主。)

const NSTimeInterval kSecondsPerDay = 60 * 60 * 24; 
- (NSInteger)daysUntilDate:(NSDate *)anotherDate { 
    NSTimeInterval secondsUntilExpired = [self timeIntervalSinceDate:anotherDate]; 
    NSTimeInterval days = secondsUntilExpired/kSecondsPerDay; 
    return (NSInteger)days; 
} 
+0

(你应该添加此作为NSDate的分类方法。) – zekel 2012-04-11 19:10:45