2015-10-06 99 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. 然后从当前日期