我想获得以点网格式接收的两个日期之间的差异。我已将日期转换为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;
}