tariq
tariq

Reputation: 529

NSFetchRequest predicate to sort by Date, using time component only

Think of the Alarm app on the iPhone, the alarms are sorted by time. Say these alarms were stored in Core Data with the date component being the actual date they were created, but with the time component chosen by a date picker. So when fetching these, you need to ignore the date component and sort them by time only.

This works if all the alarms are created on the same date:

fetchRequest.sortDescriptors = [NSSortDescriptor(key: date, ascending: true)]

But if they're created on separate days, obviously the ones created first are listed first by date, and sorted by time within each date group. I want to completely ignore the date component when doing this sort and order everything by the time component only.

Upvotes: 1

Views: 502

Answers (1)

vadian
vadian

Reputation: 285079

  • Create a global date formatter in the NSManagedObject subclass

    let timeFormatter : DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "HH:mm:ss"
        return formatter
    }()
    
  • and a computed property

    @objc var time : String {
        return timeFormatter.string(from: date)
    }
    
  • Then fetch the records unsorted and sort them manually

    let sortedRecords = records.sorted{ $0.time < $1.time }
    

Upvotes: 2

Related Questions