【问题标题】:How to get a local formatted date patterned string in iOS? [duplicate]如何在 iOS 中获取本地格式化的日期模式字符串? [复制]
【发布时间】:2012-08-20 22:57:48
【问题描述】:

可能重复:
How to determine if locale's date format is Month/Day or Day/Month?

我现在已经挣扎了一段时间,但我被困住了!我要么需要格式为“mm-dd-yyyy”或“08-25-2012”的本地格式化模式日期字符串。我该怎么做?使用dateFormat?请帮帮我!

【问题讨论】:

    标签: objective-c ios ios5 nsdate nsdateformatter


    【解决方案1】:

    NSDateFormatter 有一个方便的类方法:

    [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterNoStyle];
    

    您可以指定 NSDateFormatterNoStyle、..ShortStyle、..MediumStyle 或..LongStyle

    【讨论】:

      【解决方案2】:

      您可以将 NSDateFormatter 与 MM-dd-yyyy 一起使用,然后使用应用于格式化程序的 NSTimeZone 来调整本地时区。

      这个:

      NSDate *date = [[NSDate alloc] init];
      NSLog(@"%@", date);
      
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
      [dateFormatter setDateFormat:@"MM-dd-yyyy hh:mm"];
      NSString *dateString = [dateFormatter stringFromDate:date];
      
      NSLog(@"%@", dateString);
      
      NSTimeZone *timeZone = [NSTimeZone localTimeZone];
      [dateFormatter setTimeZone:timeZone];
      NSLog(@"adjusted for timezone: %@", [dateFormatter stringFromDate:date]);
      

      输出:

      2012-08-26 08:30:53.741 Craplet[2585:707] 2012-08-26 12:30:53 +0000
      2012-08-26 08:30:53.742 Craplet[2585:707] 08-26-2012 08:30
      2012-08-26 08:30:53.743 Craplet[2585:707] adjusted for timezone: 08-26-2012 08:30
      

      【讨论】:

      • 谢谢!这就像一个魅力。然而,我真正想要的是以某种方式获得 LOCAL dateFormat。最好在 NSString 中。你能帮我解决这个问题吗?
      • 我更新了如何使用本地时区。我添加 hh:mm 只是为了展示它是本地的。
      猜你喜欢
      • 2018-03-13
      • 2018-01-08
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多