swift - 自定义本地日期格式

标签 swift localization internationalization date-formatting

使用 swift,我希望我的自定义 dateFormatter.dateFormat 是 MMM-d 或 d-MMM,具体取决于用户的位置。如果我使用默认的 short.medium.etc 样式,这似乎很容易,但出于设计/布局方面的考虑,我需要这种自定义格式。

有什么帮助吗?

最佳答案

您可以读取当前设备区域设置并相应地设置格式。

var dateFormat: String
switch NSLocale.currentLocale().localeIdentifier {
    case "en_US": dateFormat = "MMM d"
    ...
    default: dateFormat = "d MMM"
}

另请查看 NSDateFormatter.dateFormatFromTemplate:

NSDateFormatter.dateFormatFromTemplate("MMM dd", options: 0, locale: NSLocale.currentLocale())

它返回适用于由您指定的元素(在本例中为月和日)组成的给定语言环境的格式和顺序,但它并不总是您需要的“MMM d”或“d MMM”。您可以运行它来查看它为每个语言环境实际生成的字符串:

let formatter: DateFormatter = DateFormatter()
for id in NSLocale.availableLocaleIdentifiers {
  let locale = NSLocale(localeIdentifier: id)
  let format = DateFormatter.dateFormat(fromTemplate: "MMM dd", options: 0, locale: locale as Locale) ?? "n/a"
  formatter.dateFormat = format
  formatter.locale = locale as Locale!
  let fd = formatter.string(from: NSDate() as Date)
  print("\(id)\t\(format)\t\(fd)")
}

关于swift - 自定义本地日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31632545/

相关文章:

asp.net-core - 无法使用 ASP.NET CORE 2.2 生成用于本地化的响应 cookie

html - 带有 Internet Explorer 的文本框中的阿拉伯数字

c++ - Linux 上的 tchar.h

ios - 将唯一对象添加到数组

localization - 本地化 clang 输出

angular - 错误 : Metadata version mismatch for module . ../node_modules/@ngx-translate/core/core.d.ts,找到版本 4,预期为 3

localization - 语言代码和语言环境代码的良好定义是什么?

ios - 如何在swift中使用for in循环递减条件?

swift - 在 macOS Mojave 上使侧边栏小部件透明

ios - 创建一个具有相同高度的静态单元格的 View 表以填充屏幕