Livevlad Livevlad - 1 year ago 67
Swift Question

iOS DateFormatter error with year 2099

I have created an extension to manage my dates parsing but I have an issue with date of 2099/12/31!

Here's my extension which gives me date object from YYYYMMdd string and reverse fonction.

extension Date {

// build date from string with YYYYMMDD format
static func dateCSDFrom(_ stringDate : String) -> Date?{
let dateFormatter = CSDDateFormatter()
return stringDate)
// reverse function
func stringCSDFromDate() -> String{
return Date.CSDDateFormatter().string(from: self)

private static func CSDDateFormatter() -> DateFormatter{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYYMMdd"
return dateFormatter

Here's my test :

let dateString = "20991231"
let date = Date.dateCSDFrom(dateString)
print("date object: \(date)")
print("date string: \(date?.stringCSDFromDate())")

And here's my output :

date object: Optional(2099-12-30 23:00:00 +0000)
date string: Optional("21001231")

As you can see I have a error of a year :(
I have the same result with year 2098, but all is correct with year 2100.

Any idea ?

Answer Source
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download