How can I format two NSDate as a time difference string (e.g. 2days ago) and make it follow the regional formatting of the device?

无人久伴 提交于 2019-12-05 04:55:31

问题


Does the standard framework support time difference formatting and create a format that follows the regional settings? I know I can break it to NSDateComponents but then I will have to append the text and create different language support files myself. I'm wondering that there may be a way to formatting the date and make it follows the regional setting simple and similar to this...

dateFormat = [[[NSDateFormatter alloc] init] autorelease]; [dateFormat setDateStyle:NSDateFormatterMediumStyle]

thanks


回答1:


you can turn on relative date formatting by doing:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.doesRelativeDateFormatting = YES;

this will give you date strings that look like "Yesterday", "Today", "Tomorrow" etc.

if that's not enough, then this might be useful: http://zetetic.net/code/nsdate-helper

that NSDate category didn't quite work for what i wanted, so i added my own function based on one that was in the category.. seems to work, but no guarantees ;) of course this only gives you a bit of the information - it doesn't give you locale formatting etc.

- (NSUInteger)daysAgoAgainstMidnight2 {
    // get a midnight version of ourself:
    NSDateFormatter *mdf = [[NSDateFormatter alloc] init];
    [mdf setDateFormat:@"yyyy-MM-dd"];
    NSDate *midnightMe = [mdf dateFromString:[mdf stringFromDate:self]];
    NSDate *midnightNow = [mdf dateFromString:[mdf stringFromDate:[NSDate date]]];

    NSDateComponents *components = [calendar components:(NSDayCalendarUnit)
                                               fromDate:midnightMe                                                             toDate:midnightNow
                                                options:0];
    return [components day];
}


来源:https://stackoverflow.com/questions/8614543/how-can-i-format-two-nsdate-as-a-time-difference-string-e-g-2days-ago-and-mak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!