farhan
farhan

Reputation: 345

How to group Arrays by Date in Swift?

I have a model which contains a date property.

I can group the dates by Dictionary(grouping..

let grouped = Dictionary(grouping: orders.results, by: { $0.createdAt })

But the issue is when doing decoding I did this:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

So my Date property accounts for time as well.

How should I go about grouping by just yyyy-MM-dd?

Upvotes: 6

Views: 5322

Answers (2)

rmaddy
rmaddy

Reputation: 318794

You can use Calendar startOfDay.

let cal = Calendar.current
let grouped = Dictionary(grouping: orders.results, by: { cal.startOfDay(for: $0.createdAt) })

Upvotes: 16

ironRoei
ironRoei

Reputation: 2209

I like grouping by day because by Date groups by time interval and this solution grouping by the day, month and year.

let groupDic = Dictionary(grouping: arr) { (pendingCamera) -> DateComponents in
    print("group arr: \(String(describing: pendingCamera.date))")
        
    let date = Calendar.current.dateComponents([.day, .year, .month], from: (pendingCamera.date)!)
        
    return date
}

Upvotes: 4

Related Questions