I know there are a lot of questions about dates and using/comparing dates within Swift, but I didn't see this specific question addressed.
Here is my issue, I have an array with objects in it, one of the object properties is a Date object created (createdDate = Date())when the record was saved. I'd like to be able to select the records that have a date from within the past X days (7, 28, etc.).
Not sure where to start any help is appreciated.
Swift has powerful tools to work with arrays. In you case you need filter your array.
let keyDate = Date(timeIntervalSinceNow: -7 * 60 * 60 * 24)
let filteredArray = originalArray.filter{ $0.createdDate > keyDate }
Check for more: https://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/
Edit: Regarding obtaining keyDate - if you exactly last 7days * 24hours * 60minutes * 60seconds - use timeIntervalSince now. If you need date based not on seconds, but by calendar, then:
let keyDate = Calendar(identifier: .gregorian).date(byAdding: .day, value: -7, to: Date())
more details at: https://developer.apple.com/documentation/foundation/calendar/2293676-date
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With