动态日期格式取决于语言和区域设置



Plz帮助我使用日期格式化程序:我需要根据选择的语言更改日期格式,并选择24小时/12小时的格式时间,所以动态更新它是一个主要的麻烦。现在我把它做成了

        [form setDateFormat:[NSString stringWithFormat:@"yyyy-MM-dd HH:mm"]];
        NSDate *normalDate = [form dateFromString:time];
        if (normalDate == nil) {
            [form setDateFormat:[NSString stringWithFormat:@"yyyy-MM-dd h:mm a"]];
            normalDate = [form dateFromString:time];
        }
        [form setDateFormat:[NSString stringWithFormat:@"MMMM dd, yyyy %@",timeF]];
        normalStr = [form stringFromDate:normalDate];

但我认为这是一个非常糟糕的方法,请帮助我制作更好的系统,这也会起作用)

我从未尝试过,但您可以尝试使用Localizable.strings文件。因此,当你本地化你的应用程序时,在Localizable.strings(英语)中,你可以有

"date_format" = "yyyy-MM-dd HH:mm";

而在Localizable.strings(OtherLanguage)中,您可以放置

"date_format" = "yyyy-MM-dd h:mm a";

在DateFormatter中进行

[form setDateFormat:NSLocalizedString(@"date_format", nil)]

不确定你真正想做什么)

请考虑使用NSDateFormatter dateFormatFromTemplate:选项:区域设置:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html#//apple_ref/occ/clm/NSDateFormatter/dateFormatFromTemplate:options:locale:例如,使用当前区域设置值([NSLocare curentLocale])或使用[dateFormatter setLocale:…],指定所选语言

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

和[dateFormatter setTimeStyle:…]将其设置为NSDateFormatterShortStyle、NSDateFormatter MediumStyle或NSDateFormatterLongStyle

自iOS 8以来,DateFormatter可以通过调用setLocalizedDateFormatFromTemplate: 来为您处理此问题

NSDateFormatter *formatter = [NSDateFormatter new];
formatter.formattingContext = NSFormattingContextDynamic;
[formatter setLocalizedDateFormatFromTemplate:@"yyyy-MM-dd HH:mm"];

最新更新