Z-Dog
Z-Dog

Reputation: 181

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?

Upvotes: 0

Views: 181

Answers (3)

Software2
Software2

Reputation: 2738

It's best to break that into a few more easily readable/maintainable lines. First, calculate the date you want, then apply a date formatter.

let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: Date())
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"

print(dateFormatter.stringFromDate(yesterday))

Upvotes: 2

nayem
nayem

Reputation: 7585

You shouldn't use fixed format for Date format strings. Because you might have users from around the world and they don't see dates in the same way.

Rather you should use template format. You just specify which components you want to show and their order like:

let dateFormatter = DateFormatter()
// dateFormatter.locale = Locale(identifier: "bn-BD") // Enable this line only at the time of your debugging/testing
dateFormatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "ddMMyyyy",
                                                options: 0,
                                                locale: dateFormatter.locale)

let date = Calendar.current.date(byAdding: .day, value: -1, to: Date())
if let date = date {
    let dateString = dateFormatter.string(from: date)
    print(dateString)
}

You shouldn't set your locale by yourself. It's done by the framework. You should only set your locale manually only at the time of testing your app.

In the above example I'm using Locale as "bn-BD" which means Bangla in Bangladesh. You can find your a list of locales here

Upvotes: 0

Fangming
Fangming

Reputation: 25261

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")
}

Upvotes: 1

Related Questions