Search code examples
swiftiphonedatecalendarnsdate

Get All Hours of The Day (in date format) from 9am tp 11pm and Save within an array in Swift


I need to get all the remaining hours of the day starting from whatever the current hour is until 11pm and save it in an array in a date format. Here is what I have written so far:

var sortedTime: [Date] = {

    let today = Date()
    var sortedTime: [Date] = []

    (0..<14).forEach {
        sortedTime.append(Calendar.current.date(byAdding: .hour, value: $0, to: today)!)            
    }

    return sortedTime
}()

In the code I have: (0..<14).forEach { This is giving me the next 14 hours but thats not what I need; I need to make sure the hours I get are between 9am and 11pm. How would I be able to set this limit?


Solution

  • When you access .hour for any calender its in a 24h format. so you need to something like this:

    let today = Date()
    var sortedTime: [Date] = []
    var calender = Calendar(identifier: .iso8601)
    calender.locale = Locale(identifier: "en_US_POSIX")
    let currentHour = calender.component(.hour, from: today)
    (0...(24-currentHour)).forEach {
        guard let newDate = calender.date(byAdding: .hour, value: $0, to: today) && calender.component(.hour, from: newDate) != 0,
            calender.component(.hour, from: newDate) <= 23 else {
            return
        }
        //convert date into desired format
        sortedTime.append(newDate)
    }