Search code examples
swiftdatedatetimensdateformatter

Take a certain amount of days off the current date and print with certain date format


How would I take a certain amount of days (take away one day) off the current date and print with certain date format to the console.

I'm currently using:

print((Calendar.current as NSCalendar).date(byAdding: .day, value: -1, to: Date(), options: [])!)

Which prints the date and time as:

yyyy-MM-dd HH:MM:SS +0000

But I want it to print like:

dd-MM-yyyy

Is this at all possible?


Solution

  • swift 3.0 version

    let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    if let yesterday = yesterday {
        print(dateFormatter.string(from: yesterday))
    }else{
        print("Date incorrectly manipulated")
    }