如何将两个NSDate格式化为时差字符串(例如2天前)并使其遵循设备的区域格式? [英] 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?

查看:87
本文介绍了如何将两个NSDate格式化为时差字符串(例如2天前)并使其遵循设备的区域格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准框架是否支持时差格式并创建遵循区域设置的格式?我知道我可以将它分解为NSDateComponents但是我必须自己附加文本并创建不同的语言支持文件。我想知道可能有一种方法来格式化日期并使其遵循区域设置简单和类似于此...

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]

谢谢

推荐答案

你可以通过这样做来打开相对日期格式:

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.

如果这还不够,那么这可能会有用: http://zetetic.net/code/nsdate-helper

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

NSDate类别并不适用于我想要的东西,所以我添加了我自己的功能基于类别中的一个..似乎工作,但没有保证;)当然这只会给你一些信息 - 它不会给你区域设置格式等。

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];
}

这篇关于如何将两个NSDate格式化为时差字符串(例如2天前)并使其遵循设备的区域格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆