NSDateFormatter 无法解析德语月份的三个字母缩写 March/June/Jul

NSDateFormatter fails parsing three letter abbreviation of German month March/June/Jul

我有一些德国日期格式为“10.Feb.2016”,即 2 位数字表示日,3 位字母表示月,4 位数字表示年。

我尝试使用日期格式 dd.MMM.yyyy,但失败了 3 个德国月:

那是因为根据docsMMM实际上代表"date abbreviation",这确实保证或暗示正好三个字母。

我如何解析一个恰好包含三个字母的月份日期,并适用于任何语言?这甚至可以用 NSDateFormatter 实现吗?

下面的代码说明了这个问题。它打印:

OK 10.Jan.2016
OK 10.Feb.2016
FAILED parsing: 10.Mär.2016
OK 10.Apr.2016
OK 10.Mai.2016
FAILED parsing: 10.Jun.2016
FAILED parsing: 10.Jul.2016
OK 10.Aug.2016
OK 10.Sep.2016
OK 10.Okt.2016
OK 10.Nov.2016
OK 10.Dez.2016

代码如下:

let dateFormatter = NSDateFormatter()
dateFormatter.timeZone   = NSTimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "dd.MMM.yyyy"
dateFormatter.locale     = NSLocale(localeIdentifier: "de_DE")

let input = [
    "10.Jan.2016",
    "10.Feb.2016",
    "10.Mär.2016",
    "10.Apr.2016",
    "10.Mai.2016",
    "10.Jun.2016",
    "10.Jul.2016",
    "10.Aug.2016",
    "10.Sep.2016",
    "10.Okt.2016",
    "10.Nov.2016",
    "10.Dez.2016",
]

for test in input
{
    if let date = dateFormatter.dateFromString(test)
    {
        print("OK \(test)")
    }
    else
    {
        print("FAILED parsing: \(test)")
    }
}

奇怪的是,当我尝试你的代码时,只有 "Mai" 有效。所有其他人都失败了。

然而,在查看该文档后,我尝试了以下更改:

dateFormatter.dateFormat = "dd.LLL.yyyy"

所有这些样本日期都有效("OK")。 LLL是"stand-alone"月份,说明如下:

The most important distinction to make between format and stand-alone forms is a grammatical distinction, for languages that require it. For example, many languages require that a month name without an associated day number be in the basic nominative form, while a month name with an associated day number should be in a different grammatical form: genitive, partitive, etc. Another common type of distinction between format and stand-alone involves capitalization...

我对德语的了解还不够多,无法判断这是否适用,但显然 NSDateFormatter 认为它适用。