2010-03-17 86 views
3

我有兩種格式的日期(MM/dd/yyyy hh:mm:ss:SS)。對於這兩個日期我已經通過使用(stringFromDate)方法將兩個日期轉換爲字符串。但我無法區分它們並在控制檯中顯示它們。請給我一個想法,我應該如何得到它? 謝謝。如何獲得兩個日期之間的差異?

回答

3

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

0

一般來說,我看到通過轉換日/年的值到扁平天處理天增量計算(通常天因爲一些起始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年整除)。

2

保留日期作爲日期,獲取它們之間的差異,然後打印差異。

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]; 
0

如果你只是想在天的差別,你可以做到這一點。 (上米希爾·梅塔的答案爲主。)

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