Sorin Lica
Sorin Lica

Reputation: 7656

Compute values in DateFormatter (Swift)

I need to convert a date to this format dd/MM/yyy^xxx where xxx = hh * 60 + mm, For example 31 Aug 2020 02:30AM in my format will be 31/08/2020^150, this format is used in communication with the server. I tried

    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yyyy^hh*60+mm"
    print(dateFormatter.string(from: Date()))

but the computation does not work, What is missing?

Upvotes: 0

Views: 104

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 52013

You can use DateComponents and DateComponentsFormatter to get the number of minutes

let date = Date()

let components = Calendar.current.dateComponents([.hour,.minute], from: date)

let compFormatter = DateComponentsFormatter()
compFormatter.allowedUnits = [.minute]

let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy^"

let string = formatter.string(from: date) + compFormatter.string(for: components)!

Upvotes: 2

Related Questions