NSDate组织

NSDate Organization

我试图以 S、M、H 格式显示时间戳,但是我在某些分钟格式的帐户上得到负数。展示比说的更好:

Chris 的推文应该是 4m,Mina 的推文应该是 6m。这是我的实现代码:

// Set Timestamp
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[entry[@"created_time"] doubleValue]];
NSDate *currentDateNTime = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *instacomponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:date];
NSInteger instahour = [instacomponents hour];
NSInteger instaminute = [instacomponents minute];
NSInteger instasecond = [instacomponents second];
NSDateComponents *realcomponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:currentDateNTime];
NSInteger realhour = [realcomponents hour];
NSInteger realminute = [realcomponents minute];
NSInteger realsecond = [realcomponents second];

NSInteger hour = realhour - instahour;
NSInteger minute = realminute - instaminute;
NSInteger second = realsecond - instasecond;

int adjustedSeconds = ((int)minute * 60) - abs((int)second);
int adjustedMinutes = adjustedSeconds / 60;

if (hour==1 > minute > 0) {
    int negmin = ((int)hour * 60) - abs((int)minute);
    int posmin = abs(negmin);
    NSString *strInt = [NSString stringWithFormat:@"%dm",posmin];
    cell.timeAgo.text = strInt;
}else if (hour>0){
    NSString *strInt = [NSString stringWithFormat:@"%ldh",(long)hour];
    cell.timeAgo.text = strInt;
}else if (hour==1){
    NSString *strInt = [NSString stringWithFormat:@"%ldh",(long)hour];
    cell.timeAgo.text = strInt;
}else if(minute == 1 > second){
    NSString *strInt = [NSString stringWithFormat:@"%lds",(long)second];
    cell.timeAgo.text = strInt;
}else{
    NSString *strFromInt = [NSString stringWithFormat:@"%dm",adjustedMinutes];
    cell.timeAgo.text = strFromInt;
}

发生这种情况的一个主要原因是时区。

尝试将时区设置为 GMT,然后再进行计算。希望对你有帮助。