대안으로, 당신은 당신이 두 날짜 사이의 차이에서 풀 수있는 달력 구성 요소에 의존하여 오류가 발생하기 쉬운 달력 연산을 피할 수 있습니다 :
NSDate *nowDate = [[NSDate alloc] init];
NSDate *targetDate = nil; // some other date here of your choosing, obviously nil isn't going to get you very far
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:dateTime
toDate:nowDate options:0];
NSInteger months = [components month];
NSInteger weeks = [components week];
NSInteger days = [components day];
NSInteger hours = [components hour];
NSInteger minutes = [components minute];
키는 단위 플래그의 설정입니다.이 키를 사용하여 날짜/시간을 세분화 할 시간 단위를 설정할 수 있습니다. 몇 시간을 원한다면 NSHourCalendarUnit을 설정하면됩니다. 증분을 시작할 단위가 더 크기 때문에 날짜가 멀어 질수록 그 값은 계속 증가 할 것입니다.
일단 구성 요소가 있으면 @ alex의 조건부 흐름을 수정하여 원하는 논리로 진행할 수 있습니다.
if (months > 1) {
// Simple date/time
if (weeks >3) {
// Almost another month - fuzzy
months++;
}
return [NSString stringWithFormat:@"%ld months ago", (long)months];
}
else if (months == 1) {
if (weeks > 3) {
months++;
// Almost 2 months
return [NSString stringWithFormat:@"%ld months ago", (long)months];
}
// approx 1 month
return [NSString stringWithFormat:@"1 month ago"];
}
// Weeks
else if (weeks > 1) {
if (days > 6) {
// Almost another month - fuzzy
weeks++;
}
return [NSString stringWithFormat:@"%ld weeks ago", (long)weeks];
}
else if (weeks == 1 ||
days > 6) {
if (days > 6) {
weeks++;
// Almost 2 weeks
return [NSString stringWithFormat:@"%ld weeks ago", (long)weeks];
}
return [NSString stringWithFormat:@"1 week ago"];
}
// Days
else if (days > 1) {
if (hours > 20) {
days++;
}
return [NSString stringWithFormat:@"%ld days ago", (long)days];
}
else if (days == 1) {
if (hours > 20) {
days++;
return [NSString stringWithFormat:@"%ld days ago", (long)days];
}
return [NSString stringWithFormat:@"1 day ago"];
}
// Hours
else if (hours > 1) {
if (minutes > 50) {
hours++;
}
return [NSString stringWithFormat:@"%ld hours ago", (long)hours];
}
else if (hours == 1) {
if (minutes > 50) {
hours++;
return [NSString stringWithFormat:@"%ld hours ago", (long)hours];
}
return [NSString stringWithFormat:@"1 hour ago"];
}
// Minutes
else if (minutes > 1) {
return [NSString stringWithFormat:@"%ld minutes ago", (long)minutes];
}
else if (minutes == 1) {
return [NSString stringWithFormat:@"1 minute ago"];
}
else if (minutes < 1) {
return [NSString stringWithFormat:@"Just now"];
}
이 아름답게 작동합니다
이 내가 함께 던진 것입니다. 감사! –
이 구현의 유일한 문제점은 하루 24 시간과 달력 하루를 구별하지 않는다는 것입니다. 즉 오후 11시와 오전 2시를 비교하는 경우 차이는 "3 시간 전"이 아닌 "어제"가되어야합니다. NSCalendar와 그 부속 NSDateComponents 클래스를 살펴보십시오. – retainCount