如何用其他符号替换日期组件分隔符?

Jor*_*n H 2 nsdateformatter ios nslocale swift

在我的应用程序中,我希望允许用户选择适合他们显示日期偏好的各种日期格式。但是,我不想定义固定的日期格式,因此我根据当前区域设置为不同的组件获取最合适的格式。我知道不同的本地人可能会使用不同的符号来分隔组件,但我想知道是否可以设置这些分隔符,同时根据该语言环境保留组件的正确顺序。

例如,在美国,以下代码返回“09/06/2014”,但在英国将返回“06/09/2014”,我想保留该顺序,但用破折号或空格替换斜线。但是我不相信我可以简单地解析返回的字符串并将 '/' 的实例替换为其他字符,因为在某些语言环境中它们可能不使用 '/'(我不确定,但似乎很有可能)。

NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale.currentLocale())
Run Code Online (Sandbox Code Playgroud)

在获取当前语言环境的最合适格式的同时,是否可以更改日期组件分隔符?

Jor*_*n H 7

我浏览了 iPad 上的所有语言,并检查了短日期格式。我发现所有语言都使用以下三个分隔符之一: / 。——

因此,为了在保留格式的同时允许自定义分隔符,我只是将这些字符替换为自定义字符。例如:

dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("MMddyyyy", options: 0, locale: NSLocale.currentLocale())
cell.dateLabel.text = dateFormatter.stringFromDate(NSDate())
cell.dateLabel.text = cell.dateLabel.text.stringByReplacingOccurrencesOfString("/", withString: " ", options: nil, range: nil)
cell.dateLabel.text = cell.dateLabel.text.stringByReplacingOccurrencesOfString(".", withString: " ", options: nil, range: nil)
cell.dateLabel.text = cell.dateLabel.text.stringByReplacingOccurrencesOfString("-", withString: " ", options: nil, range: nil)
Run Code Online (Sandbox Code Playgroud)

我很高兴找到更好的解决方案。