Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group Arrays by Date in Swift?

Tags:

ios

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?

like image 735
farhan Avatar asked Jun 14 '18 06:06

farhan


2 Answers

You can use Calendar startOfDay.

let cal = Calendar.current
let grouped = Dictionary(grouping: orders.results, by: { cal.startOfDay(for: $0.createdAt) })
like image 164
rmaddy Avatar answered Nov 13 '22 20:11

rmaddy


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
}
like image 4
ironRoei Avatar answered Nov 13 '22 20:11

ironRoei