Best way to define an array for the timeline, which might be more general

I have one array of strings, how can I define it better than the current one? It works for me, but it looks strange.

var arrTimelineEntry = ["12 am", "1 am", "2 am", "3 am", "4 am", "5 am", "6 am", "7 am","8 am", "9 am", "10 am", "11 am","12 pm", "1 pm", "2 pm", "3 pm", "4 pm", "5 pm", "6 pm", "7 pm", "8 pm", "9 pm", "10 pm", "11 pm"]

      

+3


source to share


2 answers


You can probably use extension

for Date

to get all daytime hours like this. And you can also easily customize them for specific requirements, and they are not hardcoded.

extension Date {
var startOfDay: Date {
    return Calendar.current.startOfDay(for: self)
}

static func dayHours() -> [String] {
    var hours = [String]()
    var today = Date(timeIntervalSince1970: 1492674841).startOfDay

    let dateFormatter = DateFormatter()
    dateFormatter.locale = NSLocale.current
    dateFormatter.dateFormat = "h a"
    dateFormatter.amSymbol = "am"
    dateFormatter.pmSymbol = "pm"

    for _ in 0...23 {
        let dateString = dateFormatter.string(from: today )
        hours.append(dateString)
        today.addTimeInterval(3600)
    }

    return hours
}

      

}



Using:

Date.dayHours()

      

+1


source


The following formatter works for different locales and languages.



let calendar = Calendar.current
let date = Date() //choose date on which DST never happened

let formatter = DateFormatter()
    formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "jm", options: 0, locale: NSLocale.current)

let dates = (0...23).map { (hour) in
    return calendar.date(bySettingHour: hour, minute: 0, second: 0, of: date)!
}

let timeLine = dates.map(formatter.string)

      

+5


source







All Articles