ドット ネット形式で受信されている 2 つの日付の差を取得したいと考えています。日付をに変換しました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;
}