1

我想按照不同国家的本地格式显示日期。

我从这里得到代码:获取用户的日期格式?(DMY, MDY, YMD)

NSString *base = @"MM/dd/yyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString *format = [NSDateFormatter dateFormatFromTemplate:base options:0 locale:locale];

但是我怎样才能dd,mm,yyyy从格式中获取顺序呢?

4

1 回答 1

5

这将为您提供以下格式currentLocale

NSString *dateComponents = @"ddMMyyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString* format = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];

要以正确的格式打印NSDate对象,请currentLocale尝试以下操作:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [NSLocale currentLocale];
[dateFormatter setLocale:locale];

NSString *dateComponents = @"ddMMyyyy";
NSString* format = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];

NSDate* date = [NSDate date];
[dateFormatter setDateFormat:format];

NSString *newDateString = [dateFormatter stringFromDate:date];
NSLog(@"Current date for locale: %@", newDateString);

如果你真的想要 dd、MM 和 yyyy 元素的数字顺序,可以像下面的代码一样完成。它不是(!)漂亮,我真的认为你应该重新考虑是否有必要获取元素的顺序。

NSString *dateComponents = @"ddMMyyyy";
NSLocale *locale = [NSLocale currentLocale];
NSString* format = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:locale];

int currentOrder = -1;
int nextIndex = 0;

int dd = -1;
int MM = -1;
int yyyy = -1;

NSString* workingSubstring;

while (dd == -1 || MM == -1 || yyyy == -1)
{
    workingSubstring = [[format substringFromIndex:nextIndex] substringToIndex:2];

    if ([workingSubstring isEqualToString:@"dd"])
    {
        dd = ++currentOrder;
        nextIndex += 3;
    }
    else if ([workingSubstring isEqualToString:@"MM"])
    {
        MM = ++currentOrder;
        nextIndex += 3;
    }
    else if ([workingSubstring isEqualToString:@"yy"])
    {
        yyyy = ++currentOrder;
        nextIndex += 5;
    }
}

NSLog(@"dd: %d, MM: %d, yyyy: %d", dd, MM, yyyy);
于 2013-09-24T06:59:17.990 回答