我從服務器獲取日期時間作爲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 –
是的,您需要根據您的要求進行一些更改。 –