-3

I am getting datetime from server as json response.Now if the date is equal to today date then i want to show it as today.if it was yesterday date then i want show as yesterday.if the time was 2 hours ago then i want to show as 2 hours.Please tell me how can implement such functionality?

TechChain
  • 8,404
  • 29
  • 103
  • 228

2 Answers2

1

in .h file :

  NSDateFormatter *commonDateFormatter;

in .m file :

-(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];
        }
    }
}
riddhi
  • 316
  • 2
  • 16
0
  1. Convert JSON to NSDate using NSDateFormatter link
  2. Get current date
  3. Get components between two days for month, week, day, hour interval unit using calendar components: fromDate: toDate: link
  4. Compare two days for it is present or past link
  5. Then show component.month .day .hour past/future from current date
Community
  • 1
  • 1
Gobi M
  • 3,243
  • 5
  • 32
  • 47