2015-10-06 64 views
-3

我從服務器獲取日期時間作爲json response.Now如果日期等於今天日期那麼我想顯示它作爲today.if它是昨天的日期,然後我想顯示爲昨天如果時間是2小時前然後我想顯示爲2小時。請告訴我如何實現這樣的功能?如何獲取顯示日期爲昨天,今天,iOS中2小時?

NSDateFormatter *commonDateFormatter; 

在.m文件:

+0

使用這個庫顯示component.month·天·小時過去/未來: - https://開頭github上。 com/kevinlawler/NSDate-TimeAgo –

+0

是的,您需要根據您的要求進行一些更改。 –

回答

1
在.h文件中

-(NSString*)convertToUTCTime:(NSString*)strDate{ 

    NSDate *currentDate = [NSDate date]; 
    myDate = [commonDateFormatter dateFromString: strDate]; 
    NSTimeInterval distanceBetweenDates = [currentDate timeIntervalSinceDate:myDate]; 
    return [self stringFromTimeInterval:distanceBetweenDates]; 
} 
- (NSString *)stringFromTimeInterval:(NSTimeInterval)interval { 
    NSInteger ti = (NSInteger)interval; 
    NSInteger minutes = (ti/60) % 60; 
    NSInteger hours = (ti/3600); 

    if (hours > 24) { 
     NSInteger days = hours/24; 
     if (days > 30) { 
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
      [dateFormatter setDateFormat:@"EEE d MMM, h:mm a"]; 
      //[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]]; 
      NSString *daydate = [dateFormatter stringFromDate:myDate]; 
      return daydate; 
     } 
     else{ 
     return [NSString stringWithFormat:@" %2ldd",(long)days]; 
     } 
    }else{ 
     if (hours == 0 && minutes < 1) { 
      return [NSString stringWithFormat:@"Today"]; 
     } 
     else if (hours == 0 && minutes < 60){ 
      return [NSString stringWithFormat:@"%2ldm ",(long)minutes]; 
     } 
     else{ 
     return [NSString stringWithFormat:@" %2ldh",(long)hours]; 
     } 
    } 
} 
+0

如果有超過幾周的時間我該如何返回只有確切的日期 – TechGuy

+0

我不明白你想說什麼 – riddhi

+0

我想問一下,如果從當前日子有太多天,那麼我只想打印日期。 – TechGuy

0
  1. 轉換JSON到的NSDate使用NSDateFormatter link
  2. 獲取當前日期
  3. 得到兩個組件之間使用日曆組件的日,月,周,日,小時間隔單位:fromDate:t大館:link
  4. 比較兩天是現在或過去link
  5. 然後從當前日期
相關問題