gpt4 book ai didi

ios - NSDateFormatter:根据 currentLocale 的日期,没有年份

转载 作者:IT王子 更新时间:2023-10-29 08:22:01 25 4
gpt4 key购买 nike

这不会太难..

我想显示没有年份的日期。例如:“8 月 2 日”(美国)或“02.08”。 (德国)它也必须适用于许多其他语言环境。

到目前为止,我唯一的想法是对年份进行正常格式化,然后从生成的字符串中删除年份部分。

最佳答案

我认为您需要看一下:

+ (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale

根据文档:

Returns a localized date format string representing the given date format components arranged appropriately for the specified locale. Return Value A localized date format string representing the date format components given in template, arranged appropriately for the locale specified by locale.

The returned string may not contain exactly those components given in template, but may—for example—have locale-specific adjustments applied.

Discussion

Different locales have different conventions for the ordering of date components. You use this method to get an appropriate format string for a given set of components for a specified locale (typically you use the current locale—see currentLocale).

The following example shows the difference between the date formats for British and American English:

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

NSString *dateFormat;
// NOTE!!! I removed the 'y' from the example
NSString *dateComponents = @"MMMMd"; //@"yMMMMd";

dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:usLocale];
NSLog(@"Date format for %@: %@",
[usLocale displayNameForKey:NSLocaleIdentifier value:[usLocale localeIdentifier]], dateFormat);

dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:gbLocale];
NSLog(@"Date format for %@: %@",
[gbLocale displayNameForKey:NSLocaleIdentifier value:[gbLocale localeIdentifier]], dateFormat);

// Output:
// Date format for English (United States): MMMM d, y
// Date format for English (United Kingdom): d MMMM y

额外代码(将其添加到上面的代码中):

// 
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
formatter.locale = gbLocale;
formatter.dateFormat = dateFormat;
NSLog(@"date: %@", [formatter stringFromDate: [NSDate date]]);

看这里: NSDateFormatter Class Reference

关于ios - NSDateFormatter:根据 currentLocale 的日期,没有年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18767330/

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