添加評論後,我需要顯示與一年前,一天前,幾分鐘前和第二次前的標籤上的評論時間,但它會返回-4425,-33434秒前的「隨機數」。NSTimeInterval顯示不正確的時間間隔
這是我在下面顯示的代碼在我的應用程序中使用。
NSString *inDateStr = [NSString stringWithFormat:@"%@",[[[dict objectForKey:@"d"] objectAtIndex:indexPath.row-1] objectForKey:@"created"]];
NSString *s = @"yyyy-MM-dd HH:mm:ss";
// about input date(GMT)
NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
inDateFormatter.dateFormat = s;
inDateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT-7.00"];
NSDate *inDate = [inDateFormatter dateFromString:inDateStr];
// about output date(IST)
NSDateFormatter *outDateFormatter = [[NSDateFormatter alloc] init];
outDateFormatter.timeZone = [NSTimeZone localTimeZone];
outDateFormatter.dateFormat = s;
NSString *outDateStr = [outDateFormatter stringFromDate:inDate];
// final output
NSLog(@"[in]%@ -> [out]%@", inDateStr, outDateStr);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateStartingString = [[NSDate alloc] init];
NSString *datestartString = outDateStr;
dateStartingString = [dateFormatter dateFromString:datestartString];
NSTimeInterval timeDifference = [[NSDate date] timeIntervalSinceDate:dateStartingString];
double minutes = timeDifference/60;
double hours = minutes/60;
double seconds = timeDifference;
double days = minutes/1440;
UILabel * dateLbl=[[UILabel alloc] initWithFrame:CGRectMake(155, [[CountArr objectAtIndex:indexPath.row] floatValue]-1, 80, 20)];
if(seconds>=86400)
dateLbl.text=[NSString stringWithFormat:@"%.0f days ", days];
else if(seconds>=3600 && seconds<86400)
dateLbl.text=[NSString stringWithFormat:@"%.0f hours ", hours];
else if (seconds>=60 && seconds<3600)
dateLbl.text=[NSString stringWithFormat:@"%.0f minutes ", minutes];
else
dateLbl.text=[NSString stringWithFormat:@"%.0f seconds ", seconds];
dateLbl.textColor=[UIColor lightGrayColor];
dateLbl.font = [UIFont systemFontOfSize:12];
[cell.contentView addSubview:dateLbl];
如果我還需要幾分鐘和幾秒鐘,該怎麼辦? –
您可以在組件中添加NSMinuteCalendarUnit | NSSecondCalendarUnit。日期只需加上HH:mm:ss。讓我知道它的工作。 – user3663584
如果我的回答對你有幫助,那麼你可以爲答案投票。 – user3663584