Cocoa touch NSDateformatter根据currentLocale设置日期格式

Cocoa touch NSDateformatter根据currentLocale设置日期格式,cocoa-touch,ios,nsdateformatter,nslocale,Cocoa Touch,Ios,Nsdateformatter,Nslocale,我可能会因为一个愚蠢的问题而发疯 我有三个字符串:年、月和日。我需要有一个基于currentLocale的正确格式的日期,因此,如果currentLocale localeIdentifier为en_US,则我的日期格式应为: 年月日 如果是fr\u fr,则日期格式应为dd/MMM/yyyy 我不认为唯一的方法是获取currentLocaleLocaleIdentifier并从一堆if-then开始 提前谢谢 Max查看NSDate组件以创建NSDate,然后使用NSDateFormatter

我可能会因为一个愚蠢的问题而发疯

我有三个字符串:年、月和日。我需要有一个基于currentLocale的正确格式的日期,因此,如果currentLocale localeIdentifier为en_US,则我的日期格式应为: 年月日

如果是fr\u fr,则日期格式应为dd/MMM/yyyy

我不认为唯一的方法是获取currentLocaleLocaleIdentifier并从一堆if-then开始

提前谢谢


Max查看NSDate组件以创建NSDate,然后使用NSDateFormatter对其进行格式化。NSDateFormatter根据格式样式(例如

nsdateformatterminiumstyle

如果我理解您的问题,您希望将
NSDateFormatter
设置为用户设备的区域设置。为此,您可以这样做:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:date];

我希望这会有所帮助。

如果您希望在格式方面比setDateStyle可用的格式更灵活,请查看我对类似问题的回答: 在Swift 3中:

let formatter=DateFormatter()
formatter.dateStyle=.medium
formatter.timeStyle=.none
formatter.locale=locale.current
让日期=日期()
让dateString=formatter.string(起始日期:date)
打印(日期字符串)

查看此链接,了解如何基于
NSDateFormatter
非常感谢。这些组件起了作用。
-(NSString *) stringFromDate:(NSDate *) date{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    [dateFormatter setLocale:[NSLocale currentLocale]];

    NSString *dateString = [dateFormatter stringFromDate:date];

    [dateFormatter release];

    return dateString;
}

-(NSDate *) dateFromString:(NSString *) dateInString{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    [dateFormatter setLocale:[NSLocale currentLocale]];

    NSDate *dateFromString = [dateFormatter dateFromString:dateInString];

    [dateFormatter release];

    return dateFromString;
}