閱讀282 返回首頁    go 阿裏雲 go 技術社區[雲棲]


iphone——日期處理

轉自:

https://blog.csdn.net/lingedeng/article/details/6996599


Dates

        NSDate類提供了創建date,比較date以及計算兩個date之間間隔的功能。Date對象是不可改變的。

        如果你要創建date對象並表示當前日期,你可以alloc一個NSDate對象並調用init初始化:

  1. NSDate *now = [[NSDate alloc] init];  

        或者使用NSDate的date類方法來創建一個日期對象。如果你需要與當前日期不同的日期,你可以使用NSDate的initWithTimeInterval...或dateWithTimeInterval...方法,你也可以使用更複雜的calendar或date components對象。

        創建一定時間間隔的NSDate對象:

[plain] view plaincopy
  1. NSTimeInterval secondsPerDay = 24 * 60 * 60;  
  2.   
  3. NSDate *tomorrow = [[NSDate alloc] initWithTimeIntervalSinceNow:secondsPerDay];  
  4.   
  5. NSDate *yesterday = [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay];  
  6.   
  7. [tomorrow release];  
  8. [yesterday release];  

        使用增加時間間隔的方式來生成NSDate對象:

[plain] view plaincopy
  1. NSTimeInterval secondsPerDay = 24 * 60 * 60;  
  2.   
  3. NSDate *today = [[NSDate alloc] init];  
  4. NSDate *tomorrow, *yesterday;  
  5.   
  6. tomorrow = [today dateByAddingTimeInterval: secondsPerDay];  
  7. yesterday = [today dateByAddingTimeInterval: -secondsPerDay];  
  8.   
  9. [today release];  

        如果要對NSDate對象進行比較,可以使用isEqualToDate:, compare:, laterDate:和 earlierDate:方法。這些方法都進行精確比較,也就是說這些方法會一直精確比較到NSDate對象中秒一級。例如,你可能比較兩個日期,如果他們之間的間隔在一分鍾之內則認為這兩個日期是相等的。在這種情況下使用,timeIntervalSinceDate:方法來對兩個日期進行比較。下麵的代碼進行了示例:

[plain] view plaincopy
  1. if (fabs([date2 timeIntervalSinceDate:date1]) < 60) ...  

NSCalendar & NSDateComponents

        日曆對象封裝了對係統日期的計算,包括這一年開始,總天數以及劃分。你將使用日曆對象對絕對日期與date components(包括年,月,日,時,分,秒)進行轉換。

        NSCalendar定義了不同的日曆,包括佛教曆,格裏高利曆等(這些都與係統提供的本地化設置相關)。NSCalendar與NSDateComponents對象緊密相關。

        你可以通過NSCalendar對象的currentCalendar方法來獲得當前係統用戶設置的日曆。

[plain] view plaincopy
  1. NSCalendar *currentCalendar = [NSCalendar currentCalendar];  
  2.   
  3. NSCalendar *japaneseCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSJapaneseCalendar];  
  4.   
  5. NSCalendar *usersCalendar = [[NSLocale currentLocale] objectForKey:NSLocaleCalendar];  
        usersCalendar和currentCalendar對象是相等的,盡管他們是不同的對象。

        你可以使用NSDateComponents對象來表示一個日期對象的組件——例如年,月,日和小時。如果要使一個NSDateComponents對象有意義,你必須將其與一個日曆對象相關聯。下麵的代碼示例了如何創建一個NSDateComponents對象:

[plain] view plaincopy
  1. NSDateComponents *components = [[NSDateComponents alloc] init];  
  2.   
  3. [components setDay:6];  
  4. [components setMonth:5];  
  5. [components setYear:2004];  
  6.   
  7. NSInteger weekday = [components weekday]; // Undefined (== NSUndefinedDateComponent)  

        要將一個日期對象解析到相應的date components,你可以使用NSCalendar的components:fromDate:方法。此外日期本身,你需要指定NSDateComponents對象返回組件。

[plain] view plaincopy
  1. NSDate *today = [NSDate date];  
  2.   
  3. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
  4.   
  5. NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];  
  6.   
  7. NSInteger day = [weekdayComponents day];  
  8. NSInteger weekday = [weekdayComponents weekday];  
  9.   
  10. 同樣你也可以從NSDateComponents對象來創建NSDate對象:  
  11. NSDateComponents *components = [[NSDateComponents alloc] init];  
  12.   
  13. [components setWeekday:2]; // Monday  
  14. [components setWeekdayOrdinal:1]; // The first Monday in the month  
  15. [components setMonth:5]; // May  
  16. [components setYear:2008];  
  17.   
  18. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
  19.   
  20. NSDate *date = [gregorian dateFromComponents:components];  

        為了保證正確的行為,您必須確保使用的組件在日曆上是有意義的。指定“出界”日曆組件,如一個-6或2月30日在公曆中的日期值產生未定義的行為。

        你也可以創建一個不帶年份的NSDate對象,這樣的操作係統會自動生成一個年份,但在後麵的代碼中不會使用其自動生成的年份。

[plain] view plaincopy
  1. NSDateComponents *components = [[NSDateComponents alloc] init];  
  2.   
  3. [components setMonth:11];  
  4. [components setDay:7];  
  5.   
  6. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
  7.   
  8. NSDate *birthday = [gregorian dateFromComponents:components];  

        下麵的示例顯示了如何從一個日曆置換到另一個日曆:

[plain] view plaincopy
  1. NSDateComponents *comps = [[NSDateComponents alloc] init];  
  2.   
  3. [comps setDay:6];  
  4. [comps setMonth:5];  
  5. [comps setYear:2004];  
  6.   
  7. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
  8.   
  9. NSDate *date = [gregorian dateFromComponents:comps];  
  10.   
  11. [comps release];  
  12. [gregorian release];  
  13.   
  14. NSCalendar *hebrew = [[NSCalendar alloc] initWithCalendarIdentifier:NSHebrewCalendar];  
  15.   
  16. NSUInteger unitFlags = NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;  
  17.   
  18. NSDateComponents *components = [hebrew components:unitFlags fromDate:date];  
  19.   
  20. NSInteger day = [components day]; // 15  
  21. NSInteger month = [components month]; // 9  
  22. NSInteger year = [components year]; // 5764  

曆法計算

        在當前時間加上一個半小時:

[plain] view plaincopy
  1. NSDate *today = [[NSDate alloc] init];  
  2.   
  3. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
  4.   
  5. NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];  
  6.   
  7. [offsetComponents setHour:1];  
  8. [offsetComponents setMinute:30];  
  9.   
  10. // Calculate when, according to Tom Lehrer, World War III will end  
  11. NSDate *endOfWorldWar3 = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];  

        獲得當前星期中的星期天(使用格裏高利曆):

[plain] view plaincopy
  1. NSDate *today = [[NSDate alloc] init];  
  2.   
  3. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
  4.   
  5. // Get the weekday component of the current date  
  6. NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];  
  7.   
  8. /*  
  9. Create a date components to represent the number of days to subtract from the current date.  
  10.   
  11. The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question.  (If today is Sunday, subtract 0 days.)  
  12. */  
  13.   
  14. NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];  
  15.   
  16. [componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];  
  17.   
  18. NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];  
  19.   
  20. /*  
  21. Optional step:  
  22. beginningOfWeek now has the same hour, minute, and second as the original date (today).  
  23.   
  24. To normalize to midnight, extract the year, month, and day components and create a new date from those components.  
  25. */  
  26.   
  27. NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: beginningOfWeek];  
  28.   
  29. beginningOfWeek = [gregorian dateFromComponents:components];  

        如何可以計算出一周的第一天(根據係統的日曆設置):

  1. NSDate *today = [[NSDate alloc] init];  
  2.   
  3. NSDate *beginningOfWeek = nil;  
  4.   
  5. BOOL ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate: today];  

        獲得兩個日期之間的間隔:

  1. NSDate *startDate = ...;  
  2. NSDate *endDate = ...;  
  3.   
  4. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
  5.   
  6. NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;  
  7.   
  8. NSDateComponents *components = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];  
  9.   
  10. NSInteger months = [components month];  
  11. NSInteger days = [components day];  

        使用Category來計算同一時代(AD|BC)兩個日期午夜之間的天數:

[plain] view plaincopy
  1. @implementation NSCalendar (MySpecialCalculations)  
  2.   
  3. -(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate {  
  4.      NSInteger startDay=[self ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:startDate];  
  5.   
  6.      NSInteger endDay=[self ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:endDate];  
  7.   
  8.      return endDay-startDay;  
  9. }  
  10.   
  11. @end  

        使用Category來計算不同時代(AD|BC)兩個日期的天數:

[plain] view plaincopy
  1. @implementation NSCalendar (MyOtherMethod)  
  2.   
  3. -(NSInteger) daysFromDate:(NSDate *) startDate toDate:(NSDate *) endDate {  
  4.   
  5.      NSCalendarUnit units=NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;  
  6.   
  7.      NSDateComponents *comp1=[self components:units fromDate:startDate];  
  8.      NSDateComponents *comp2=[self components:units fromDate endDate];  
  9.   
  10.      [comp1 setHour:12];  
  11.      [comp2 setHour:12];  
  12.   
  13.      NSDate *date1=[self dateFromComponents: comp1];  
  14.      NSDate *date2=[self dateFromComponents: comp2];  
  15.   
  16.      return [[self components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0] day];  
  17. }  
  18.   
  19. @end  

        判斷一個日期是否在當前一周內(使用格裏高利曆):

[plain] view plaincopy
  1. -(BOOL)isDateThisWeek:(NSDate *)date {  
  2.   
  3.      NSDate *start;  
  4.      NSTimeInterval extends;  
  5.   
  6.      NSCalendar *cal=[NSCalendar autoupdatingCurrentCalendar];  
  7.      NSDate *today=[NSDate date];  
  8.   
  9.      BOOL success= [cal rangeOfUnit:NSWeekCalendarUnit startDate:&start interval: &extends forDate:today];  
  10.   
  11.      if(!success)  
  12.         return NO;  
  13.   
  14.      NSTimeInterval dateInSecs = [date timeIntervalSinceReferenceDate];  
  15.      NSTimeInterval dayStartInSecs= [start timeIntervalSinceReferenceDate];  
  16.   
  17.      if(dateInSecs > dayStartInSecs && dateInSecs < (dayStartInSecs+extends)){  
  18.           return YES;  
  19.      }  
  20.      else {  
  21.           return NO;  
  22.      }  
  23. }  
方法2:
+(NSString*)getyDealDateToString:(int)day{
    NSDate *curDate = [NSDate date];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSDateComponents* comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate];
    comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate]; 
    [comps setMonth:[comps month]+1];
    [comps setDay:day];
    NSDate *tDateMonth = [calendar dateFromComponents:comps];
    NSString *dateStr=[NSString stringWithFormat:@"%@",tDateMonth];
    return dateStr;
}

參數:day天數,可以是負數
用法:
NSLog(@"%@",[你的類名 getyDealDateToString:-30]);
如果今天的日期是2013-03-31 21:56:23
則輸出:2013-02-28 21:56:23

最後更新:2017-04-03 05:39:47

  上一篇:go C# Excel數據驗重及Table數據驗重
  下一篇:go Storm專題一、Storm DRPC 分布式計算