我正在尝试从国家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, 12100
:01 January, 2000