dateFormatter返回带有两位数字年份说明符的错误日期

时间:2019-02-21 06:31:16

标签: ios swift nsdateformatter dateformatter

我正在尝试从国家ID字符串“ 000101xxxxxxx”中解析日期字符串。

func getDateOfBirth(from nationalId: String) -> Date? {
    if let substring = nationalId[0 ..< 6] {
        let dobString = String(substring)
        let formatter = DateFormatter()

        formatter.dateFormat = "yyMMdd"
        formatter.twoDigitStartDate = Calendar.current.date(byAdding: .year, value: -100, to: Date())

        return formatter.date(from: dobString)
    }

    return nil
}

之后,我将此日期转换为可读格式:

func printDate(_ date: Date) {
    let formatter = DateFormatter()

    formatter.dateFormat = "dd MMMM, yyyy"

    if let date = date {
        return formatter.string(from: date)
    }
}

最后:

if let dob = getDateOfBirth(from: "000101xxxxxxx") {
    printDate(dob)
}

我得到以下日志:   我期望的01 January, 1210001 January, 2000

0 个答案:

没有答案