Search code examples
iosswiftnsdateformatter

Using DateFormatter to show future dates instead of past dates in Swift


I have the following code where input is being sent as 10/01/77 and DateFormatter is converting it into 1977 but the expected year is 2077. How can this be controlled?

let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yy"
let _tmpDate = formatter.date(from: "10/01/77")
// _tmpDate is getting converted to 1977 instead of 2077

However, if the date is presented as 02/26/09, the expected year is 2009 and not 2109.


Solution

  • Use DateFormatter twoDigitStartDate. Create a date for whatever year you need.

    let formatter = DateFormatter()
    formatter.twoDigitStartDate = Calendar.current.date(from: DateComponents(year: 1980))
    formatter.dateFormat = "MM/dd/yy"
    let _tmpDate = formatter.date(from: "10/01/77") // gives 2077
    

    Change 1980 to whatever year meets your needs.