0

I'm looking to sort my array by time but rather than from 0000h to 2359h, I want it to be sorted from 0600h and end at 0559h. The line of code below sorts my array of alarms by their date value (which is of Date type), but obviously from 0000h onwards. Is there a simple way to sort from a certain point or do I need to divide the array into two (one from 6am to midnight, and one from midnight to 5:59am)?

array.sort { $0.time.date.compare($1.time.date) == .orderedAscending }
4
  • What type are your dates? Or rather the elements of your array? Commented Jan 17, 2020 at 17:17
  • What do you mean sort from a certain point? Like only sort elements after a certain index or with a value greater than a particular value? Commented Jan 17, 2020 at 17:28
  • Can you elaborate on exactly what you're looking for? Commented Jan 17, 2020 at 17:45
  • Your question isn't clear at all. You have Dates, not hours, that's strange behavior. Show examples and the expected result with different edges cases. Commented Jan 17, 2020 at 17:46

1 Answer 1

1

First extend Date to make it easier to extract hour and minute components from it.

extension Date {
    var hour: Int { Calendar.current.component(.hour, from: self) }
    var minute: Int { Calendar.current.component(.minute, from: self) }
}

Then you can create a custom sort as shown in this post:

array.sort {  
    if $0.time.date.hour < 6, $1.time.date.hour >= 6 { return false }
    if $1.time.date.hour < 6, $0.time.date.hour >= 6 { return true  }
    return ($0.time.date.hour, $0.time.date.minute) < ($1.time.date.hour, $1.time.date.minute)
}

Playground testing:

let date1 = DateComponents(calendar: .current, year: 2016, month: 12, day: 10, hour: 23, minute: 0).date!
let date2 = DateComponents(calendar: .current, year: 2017, month: 11, day: 5, hour: 3, minute: 0).date!
let date3 = DateComponents(calendar: .current, year: 2018, month: 8, day: 6, hour: 6, minute: 0).date!
let date4 = DateComponents(calendar: .current, year: 2019, month: 9, day: 27, hour: 7, minute: 0).date!
let date5 = DateComponents(calendar: .current, year: 2020, month: 10, day: 30, hour: 2, minute: 0).date!

var dates = [date1,date2,date3,date4,date5]

dates.sort {
    if $0.hour < 6, $1.hour >= 6 { return false }
    if $1.hour < 6, $0.hour >= 6 { return true  }
    return ($0.hour,$0.minute) < ($1.hour,$1.minute)
}
dates  // "Aug 6, 2018 at 6:00 AM", "Sep 27, 2019 at 7:00 AM", "Dec 10, 2016 at 11:00 PM", "Oct 30, 2020 at 2:00 AM", "Nov 5, 2017 at 3:00 AM"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.