Monday 17 February 2014

Get Date and Time difference with different format with my custom method

You can get difference with bellow code

   NSString *strDifference = [self getDateDifferencewithTimeDay:yourOldDateString strDate2:[self StringFromDate:[NSDate date]]];
NSLog(@"\n Difference  =====>> %@", strDifference);

 Here i set old string and current string to get difference between that both dates.
Here i use two methods in above code one is getDateDifferencewithTimeDay for get difference between that dates and second is StringFromDate for get data in string format.


-(NSString *)getDateDifferencewithTimeDay:(NSString *)strDate1 strDate2:(NSString *)strDate2{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    NSDate *Date1;
    NSDate *Date2;
    NSString *strAnswer;
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    Date1 = [formatter dateFromString:strDate1];
    Date2 = [formatter dateFromString:strDate2];
    
    NSTimeInterval timeDifference = [Date2 timeIntervalSinceDate:Date1];
    
    double minutes = timeDifference / 60;
    
    double hours = minutes / 60;
    
    double seconds = timeDifference;
    
    double days = minutes / 1440;
    
    if (seconds < 60) {
        strAnswer = [NSString stringWithFormat:@"%.0f Seconds ago.",seconds];
    }
    else if (minutes < 60){
        strAnswer = [NSString stringWithFormat:@"%.0f Minutes ago.",minutes];
    }
    else if (hours < 24){
        strAnswer = [NSString stringWithFormat:@"%.0f Hours ago.",hours];
    }
    else{
        strAnswer = [NSString stringWithFormat:@"%.0f Days ago.",days];
    }
    return strAnswer;
}

And also this bellow method is for convert NSDate to NSString format

-(NSString *)StringFromDate:(NSDate *)DateLocal{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [dateFormat stringFromDate:DateLocal];
    NSLog(@"Date is HERE  =====>> %@",dateString);
    return dateString;
}