我从服务器获取日期时间作为json response.Now如果日期等于今天日期那么我想显示它作为today.if它是昨天的日期,然后我想显示为昨天如果时间是2小时前然后我想显示为2小时。请告诉我如何实现这样的功能?如何获取显示日期为昨天,今天,iOS中2小时?
NSDateFormatter *commonDateFormatter;
在.m文件:
我从服务器获取日期时间作为json response.Now如果日期等于今天日期那么我想显示它作为today.if它是昨天的日期,然后我想显示为昨天如果时间是2小时前然后我想显示为2小时。请告诉我如何实现这样的功能?如何获取显示日期为昨天,今天,iOS中2小时?
NSDateFormatter *commonDateFormatter;
在.m文件:
-(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];
}
}
}
使用这个库显示component.month·天·小时过去/未来: - https://开头github上。 com/kevinlawler/NSDate-TimeAgo –
是的,您需要根据您的要求进行一些更改。 –