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?
Asked
Active
Viewed 877 times
2 Answers
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
-
what if there are more than weeks the how i return only th exact date – TechChain Oct 06 '15 at 09:40
-
-
i want to ask what if there are too many days from current days then i want to print the date only. – TechChain Oct 06 '15 at 10:05
-
-
if you want display only date then change format of date from [dateFormatter setDateFormat:@"EEE d MMM, h:mm a"] to [dateFormatter setDateFormat:@"yyyy:MM:dd"] – riddhi Oct 06 '15 at 10:26
-
I don't understand this code. How can `hours == 0 && minutes < 1 == "Today"`? – Droppy Oct 06 '15 at 10:30
0
- Convert JSON to NSDate using NSDateFormatter link
- Get current date
- Get components between two days for month, week, day, hour interval unit using calendar components: fromDate: toDate: link
- Compare two days for it is present or past link
- Then show component.month .day .hour past/future from current date