gpt4 book ai didi

ios - 使用 setDoesRelativeDateFormatting : YES and setDateFormat: with NSDateFormatter

转载 作者:可可西里 更新时间:2023-11-01 05:05:47 25 4
gpt4 key购买 nike

NSDateFormatter 对生成诸如“今天”、“明天”、“昨天”等当前语言支持的相关日期有很好的支持。一个很大的优势是所有这些都已经为您本地化了——您不需要翻译字符串。

您可以通过以下方式开启此功能:

[dateFormatter setDoesRelativeDateFormatting: YES];

不利的一面是,这似乎只适用于使用一种预定义格式的实例,例如:

[dateFormatter setDateStyle: NSDateFormatterShortStyle];

如果您将日期格式化程序设置为使用自定义格式,如下所示:

[dateFormatter setDateStyle: @"EEEE"];

然后当你打电话时:

[dateFormatter stringFromDate: date];

……你只会得到一个空字符串。

我希望能够在可能的情况下获取相关字符串,而在无法获取的情况下使用我自己的自定义格式。

最佳答案

我在 NSDateFormatter 上设置了一个类别来为此提供解决方法。代码后有解释。

在 NSDateFormatter+RelativeDateFormat.h 中:

@interface NSDateFormatter (RelativeDateFormat)
-(NSString*) relativeStringFromDateIfPossible:(NSDate *)date;
@end

在 NSDateFormatter+RelativeDateFormat.m 中:

@implementation NSDateFormatter (RelativeDateFormat)
-(NSString*) relativeStringFromDateIfPossible:(NSDate *)date
{
static NSDateFormatter *relativeFormatter;
static NSDateFormatter *absoluteFormatter;

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
const NSDateFormatterStyle arbitraryStyle = NSDateFormatterShortStyle;

relativeFormatter = [[NSDateFormatter alloc] init];
[relativeFormatter setDateStyle: arbitraryStyle];
[relativeFormatter setTimeStyle: NSDateFormatterNoStyle];
[relativeFormatter setDoesRelativeDateFormatting: YES];

absoluteFormatter = [[NSDateFormatter alloc] init];
[absoluteFormatter setDateStyle: arbitraryStyle];
[absoluteFormatter setTimeStyle: NSDateFormatterNoStyle];
[absoluteFormatter setDoesRelativeDateFormatting: NO];
});

NSLocale *const locale = [self locale];
if([relativeFormatter locale] != locale)
{
[relativeFormatter setLocale: locale];
[absoluteFormatter setLocale: locale];
}

NSCalendar *const calendar = [self calendar];
if([relativeFormatter calendar] != calendar)
{
[relativeFormatter setCalendar: calendar];
[absoluteFormatter setCalendar: calendar];
}

NSString *const maybeRelativeDateString = [relativeFormatter stringFromDate: date];
const BOOL isRelativeDateString = ![maybeRelativeDateString isEqualToString: [absoluteFormatter stringFromDate: date]];

if(isRelativeDateString)
{
return maybeRelativeDateString;
}
else
{
return [self stringFromDate: date];
}
}
@end

这是如何运作的?

它使用(任意)标准格式维护两个日期格式化程序。它们的格式相同,只是一个将提供相对日期字符串而另一个不提供。

通过使用两个格式化程序格式化给定的日期,可以查看相对日期格式化程序是否给出了特殊的相对日期。当两个格式化程序给出不同结果时,有一个特殊的相对日期。

  • 如果一个特殊的相对日期字符串,则返回该特殊的相对日期字符串。
  • 如果没有特殊的相对日期字符串,则使用原始格式化程序作为后备,并使用您在其上定义的格式设置。

您可以找到更多关于 dispatch_once here 的信息.

限制……

该实现不处理您可能已放入格式字符串中的时间组件。当相对日期字符串可用时,您的格式字符串将被忽略,您将获得相对日期字符串。

关于ios - 使用 setDoesRelativeDateFormatting : YES and setDateFormat: with NSDateFormatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20331450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com