Relative string from NSDate

后端 未结 5 1081
滥情空心
滥情空心 2020-12-03 00:05

Does anyone know of a library or something that will convert an NSDate into strings like the examples below?

1 hour ago
yesterday
last Thursday
2 days ago
la         


        
5条回答
  •  不知归路
    2020-12-03 00:53

    DO NOT use your own custom string translation. Writing your own translation that does something like "3 seconds ago" not only has the problem of needing to be updated constantly, but it also does not localize into other languages.

    Instead, use Apple's built in NSDateFormatter:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.doesRelativeDateFormatting = YES;
    formatter.locale = [NSLocale currentLocale];
    formatter.dateStyle = NSDateFormatterShortStyle;
    formatter.timeStyle = NSDateFormatterShortStyle;
    NSString *timeString = [formatter stringFromDate:self.date];
    

    This will output something like "Today, 11:10 PM", or "7/17/14, 5:44 AM".

提交回复
热议问题