你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS-字符串轉化成NSDate類型,計算與當前時間的相差,月數,天數

iOS-字符串轉化成NSDate類型,計算與當前時間的相差,月數,天數

編輯:IOS開發綜合

NSString *dateStr=[dic objectForKey:@"date"];// 2012-05-17 11:23:23
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
     NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; 
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromdate=[format dateFromString:dateStr];
    NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
     NSLog(@"fromdate=%@",fromDate);
    [format release];
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    NSLog(@"enddate=%@",localeDate);
    NSDateComponents *components = [gregorian components:unitFlags fromDate:fromDate toDate:localeDate options:0]; 
    NSInteger months = [components month]; 
    NSInteger days = [components day];//年[components year]
    NSLog(@"month=%d",months);
    NSLog(@"days=%d",days);
    [gregorian release];
    if (months==0&&days==0) {
        dateStr=[[dateStr substringFromIndex:11]substringToIndex:5];
        cell.textLabel.text=[NSString stringWithFormat:@"今天 %@",dateStr];//今天 11:23
    }else if(months==0&&days==1){
        dateStr=[[dateStr substringFromIndex:11]substringToIndex:5];
        cell.textLabel.text=[NSString stringWithFormat:@"昨天 %@",dateStr];//昨天 11:23
    }else{
        dateStr=[dateStr substringToIndex:10];
        cell.textLabel.text=dateStr;
    }

 


摘自 shijiucdy的專欄

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved