Sriteja Chilakamarri Sriteja Chilakamarri - 4 years ago 121
Swift Question

Getting wrong dates when Trying to display start and end date in swift

I am trying to get the current date and pass it as Startdate. I want end date to be 90 days before the start date.

func transDate(){


let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD"
let startDate = dateFormatter.string(from: date)



let eDate = Calendar.current.date(byAdding: .day, value: -90, to: Date())
let enDate = dateFormatter.string(from: eDate!)


print("Date \(startDate) \(enDate)")



}


When i try to print them i get

Date 2017-02-38 2016-11-314


Can anyone help me how to fix this ?

Answer Source

Dateformat you can get the difference from here, use the dateformat

dateFormatter.dateFormat = "yyyy-MM-dd"

instead of

dateFormatter.dateFormat = "YYYY-MM-DD"

for example purpose

    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let startDate = dateFormatter.string(from: date)



    let eDate = Calendar.current.date(byAdding: .day, value: -90, to: Date())
    let enDate = dateFormatter.string(from: eDate!)


    print("Date \(startDate) \(enDate)")

output

enter image description here

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