iphone - 按照本地格式显示日期

标签 iphone ios objective-c date nsdateformatter

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

我从这里得到了代码:Get the user's date format? (DMY, MDY, YMD)

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

但是如何从格式中获取dd,mm,yyyy的顺序?

最佳答案

这将为您提供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);

关于iphone - 按照本地格式显示日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18974800/

相关文章:

iphone - 如何在表格单元格上滑动并使其调用函数?

iphone - AppStore,我有一个应用正在审核中,我可以将其由自动发布改为手动发布吗?

ios - UITextView 末尾的额外空间

ios - UITableView 编辑模式阻止单元格重新分配并减慢 dequeueReusableCellWithIdentifier

ios - iOS 应用程序中的 sendbird 应用程序 ID 出现问题

iphone - 如何从 Web 浏览器控件中托管的 HTML 在 Safari 中打开链接?

ios - Alamofire 错误 : Operation couldn't be completed. 软件导致连接中止

ios - 在 Swift 中使用 Facebook Messenger SDK

ios - 在闭包中快速捕捉 self

ios - 将 iOS 应用程序带到前台时更改屏幕