Skip to content

Instantly share code, notes, and snippets.

@jklausa
Last active September 11, 2015 16:09
Show Gist options
  • Save jklausa/a1cba75ca6d54065280d to your computer and use it in GitHub Desktop.
Save jklausa/a1cba75ca6d54065280d to your computer and use it in GitHub Desktop.
/* Explanation: I need to have a string that says "x days ago" BUT, if there's a word in the languague for it
(like "yesterday" in english, or "gestern" and "vorgestern" in geman), use that instead. Obviously, it needs to
support multiple languages, so no hardcoding of strings if possible.
I've inherited a .stringsdict with "x days ago" in some languages (that's the @"RELATIVE_DAYS_NEGATIVE").
I wanna avoid having external dependency just for that, but can be convinced otherwise.
How horrible is this?
*/
- (void)daysAgoStringForDaysAgo:(NSInteger)days {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeStyle = NSDateFormatterNoStyle;
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
dateFormatter.doesRelativeDateFormatting = YES;
self.dateFormatter = dateFormatter;
NSDate *nowDate = [NSDate date];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = days;
NSDate *offsetDate = [calendar dateByAddingComponents:dateComponents toDate:nowDate options:0];
NSString *relativeString = [dateFormatter stringFromDate:offsetDate];
dateFormatter.doesRelativeDateFormatting = NO;
NSString *notRelativeString = [dateFormatter stringFromDate:offsetDate];
if ([relativeString isEqualToString:notRelativeString]) {
NSString *title = [NSString stringWithFormat:NSLocalizedString(@"RELATIVE_DAYS_NEGATIVE", nil), @(labs(days))];
return title;
}
return relativeString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment