I will answer in objective-C because i'm sure you can extract the swift out of it, here is a method that will react differently if the given date is earlier than today, today exactly, or a week from now, or month, or year(s).
+ (NSString*)cellDateFormatWithDate:(NSDate*)date{
NSCalendarUnit units = NSDayCalendarUnit | NSWeekOfYearCalendarUnit |
NSMonthCalendarUnit | NSYearCalendarUnit;
// if `date` is before "now" (i.e. in the past) then the components will be positive
NSDateComponents *components = [[NSCalendar currentCalendar] components:units
fromDate:date
toDate:[NSDate date]
options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
if (components.year > 0) {
[formatter setDateFormat:@"dd/MM/yy"];
} else if (components.month > 0) {
[formatter setDateFormat:@"dd/MM/yy"];
} else if (components.weekOfYear > 0) {
[formatter setDateFormat:@"dd/MM HH:mm"];
} else if (components.day > 0) {
if (components.day > 1) {
[formatter setDateFormat:@"dd/MM HH:mm"];
} else {
[formatter setDateFormat:@"dd/MM HH:mm"];
}
} else {
[formatter setDateFormat:@"HH:mm"];
}
NSString *cellDate = [formatter stringFromDate:date];
return cellDate;
}
To fit your question, you just need to add an
NSString* relativeString;
and in each if/else
, change it accordingly
relativeString = @"Today";
relativeString = @"Yesterday";
relativeString = @"A week ago";
and so on.
This other method does pretty much the same but with second/minute accuracy
+ (NSString *)dateDiff:(NSString *)origDate{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
NSDate *convertedDate = [df dateFromString:origDate];
NSDate *todayDate = [NSDate date];
double ti = [convertedDate timeIntervalSinceDate:todayDate];
ti = ti * -1;
if(ti < 1) {
return NSLocalizedString(@"REL_TIME_NOW", nil);
} else if (ti < 60) {
return NSLocalizedString(@"REL_TIME_LESS_THAN_MINUTE", nil);
} else if (ti < 3600) {
int diff = round(ti / 60);
if (diff < 2){
return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_MINUTE", nil), diff];
}else{
return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_MINUTES", nil), diff];
}
} else if (ti < 86400) {
int diff = round(ti / 60 / 60);
if (diff < 2){
return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_HOUR", nil), diff];
}else{
return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_HOURS", nil), diff];
}
} else {
int diff = round(ti / 60 / 60 / 24);
if (diff < 2){
return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_DAY", nil), diff];
}else{
return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_DAYS", nil), diff];
}
}
}
Though I can't be bothered renaming all my localized strings, they just show
"less than a minute ago"
"%d minute ago"
"%d minutes ago"
"%d hour ago
"
and so on