gpt4 book ai didi

arrays - swift 阵列。尝试根据当前时间查找数组中的下一个时间

转载 作者:行者123 更新时间:2023-11-30 13:59:03 28 4
gpt4 key购买 nike

我有当前时间和这组时间。我想计算出下一次与当前时间最接近的时间。

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute], fromDate: date)
let hour = components.hour
let minutes = components.minute
let currentTime = "\(hour)" + ":" + "\(minutes)" //output 15:24

let timesArray = ["5:45", "6:35", "7:00", "7:30", "7:50", "8:20", "8:40", "9:15", "10:10", "11:10", "12:40", "14:15", "14:50", "15:40", "16:10", "17:10", "17:40", "18:40", "19:25", "20:50"]

最佳答案

let date = NSDate()
let timesArray = ["5:45", "6:35", "7:00", "7:30", "7:50", "8:20", "8:40", "9:15", "10:10", "11:10", "12:40", "14:15", "14:50", "15:40", "16:10", "17:10", "17:40", "18:40", "19:25", "20:50"]

// create a method to convert your time to minutes
func stringToMinutes(input:String) -> Int {
let components = input.componentsSeparatedByString(":")
let hour = Int((components.first ?? "0")) ?? 0
let minute = Int((components.last ?? "0")) ?? 0
return hour*60 + minute
}

//create an array with the minutes from the original array
let timesMinutesArray:[Int] = timesArray.map { stringToMinutes($0) }

let dayMinute = stringToMinutes("15:24")
// filter out the times that has already passed
let filteredTimesArray = timesMinutesArray.filter{$0 > dayMinute }

// get the first time in your array
if let firstTime = filteredTimesArray.first {
// find its position and extract it from the original array
let item = timesArray[timesMinutesArray.indexOf(firstTime)!] // "15:40"
}

如果需要,您还可以创建一个扩展以在代码中的任何位置使用它,如下所示:

extension String {
var hourMinuteValue: (hour:Int,minute:Int) {
guard
let hour = Int(componentsSeparatedByString(":").first ?? ""),
let minute = Int(componentsSeparatedByString(":").last ?? "")
where componentsSeparatedByString(":").count == 2
else { return (0,0) }
return (hour,minute)
}
var dayMinute:Int {
return hourMinuteValue.hour*60 + hourMinuteValue.minute
}
}

let time = "15:24"

let times = ["5:45", "6:35", "7:00", "7:30", "7:50", "8:20", "8:40", "9:15", "10:10", "11:10", "12:40", "14:15", "14:50", "15:40", "16:10", "17:10", "17:40", "18:40", "19:25", "20:50"]

let minutes = times.map{ $0.dayMinute }

let filteredMinutes = minutes.filter{ $0 > time.dayMinute }

if let firstTime = filteredMinutes.first {
let item = times[minutes.indexOf(firstTime)!] // "15:40"
}

关于arrays - swift 阵列。尝试根据当前时间查找数组中的下一个时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33203965/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com