0

我想获得以点网格式接收的两个日期之间的差异。我已将日期转换为NSDate. 但我无法获得日期之间的确切差异(小时、分钟和秒字段为零)。我正在使用下面的方法。

- (NSString*)calculateTimeFromDate :(NSDate*)date {

NSDate *createdDate;
NSDate *todayDate;


NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:SS"];

NSString *str = [formatter  stringFromDate:date];
NSString *str1= [formatter stringFromDate:[NSDate date]];


createdDate = [formatter dateFromString:str];;
todayDate = [formatter dateFromString:str1];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];


NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate:createdDate
                                              toDate:todayDate options:0];
NSInteger timeDifference = [components day];

int days = timeDifference;
NSString *timeStr;
if(days>0) {

    if(days == 1)  timeStr = [NSString stringWithFormat:@"%.0i %@",days, LString(@"DAY")];
    else           timeStr = [NSString stringWithFormat:@"%.0i %@ ",days, LString(@"DAYS")];
   } else {

    int hours = [components hour];
    if(hours >0){

        if(hours ==1)  timeStr = [NSString stringWithFormat:@"%.0i %@",hours, LString(@"HOUR")];
        else           timeStr = [NSString stringWithFormat:@"%.0i %@",hours, LString(@"HOURS")];
    } else {

        int minutes = [components minute];
        if(minutes>0) {

            if(minutes ==1 )   timeStr = [NSString stringWithFormat:@"%.0i %@",minutes, LString(@"MINUTE")];
            else               timeStr = [NSString stringWithFormat:@"%.0i %@",minutes, LString(@"MINUTES")];
        } else {

            int seconds =[components second];
            if(seconds >5)  timeStr=[NSString stringWithFormat:@"%.0i %@",seconds, LString(@"SECONDS")];
            else            timeStr = LString(@"JUST_NOW");
        }
    }
}
if(![timeStr isEqualToString:LString(@"JUST_NOW")])   timeStr = [timeStr stringByAppendingFormat:@" %@", LString(@"AGO")];
NSLog(@"%@",timeStr);
return timeStr;
}
4

3 回答 3

3

试试这个:https ://github.com/jonhocking/PrettyTimestamp

这是 NSDate 上一个非常酷的类别,它返回两个日期之间的差异,作为一个很好的字符串,比如“一分钟前”

如果它不是你想要的,我相信它会帮助你朝着正确的方向前进,或者可以修改它以返回你喜欢的字符串。

于 2013-08-24T10:57:20.890 回答
0

不要重新发明轮子,使用库来完成任务。

那里有几个 github 项目,但这是我认为最好的FormatterKit之一,由 AFNetworking 的作者 Mattt Thomposon 创建和维护。

它工作得很好,它也为本地化提供了支持。

于 2013-08-24T11:05:20.330 回答
0

• 可以使用 - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate 计算两个日期之间的差异

NSTimeInterval timeInterval  = [todayDate timeIntervalSinceDate:createdDate];

• 将timeInterval 转换为小时、分钟和秒。

int minutes = floor(timeInterval/60);
int seconds = trunc(timeInterval - minutes * 60);
int hours = minutes / 60;
于 2013-08-24T10:52:11.070 回答