我有一个字符串数组如何比当前更好地定义它?它对我有用,但看起来很奇怪。
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"]
答案 0 :(得分:5)
以下格式化程序适用于不同的语言环境和语言。
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)
答案 1 :(得分:1)
可能您可以使用extension
的{{1}}来获取这样的全天工作时间。您也可以根据特定要求轻松定制它们,并且它们不是硬编码的。
Date
}
用法:
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
}