如何从一系列日期获得最接近当前时间的时间? iOS,Swift 3

时间:2017-03-14 08:27:58

标签: ios swift swift3 nsdate

我正在尝试从Date对象数组中获取最接近当前时间(小时和分钟)的时间(小时和分钟)。

我想要的不是比较和找到最接近的日期而是时间(仅限小时和分钟)。是否有任何iOS方式/ Swfit 3可以有效地做到这一点?

修改 最接近的时间是顺时针“向前移动”而不是向后移动的时间。

EDIT2: 这是一个示例:

import Foundation

let userCalendar = Calendar.current

var firstDateComponents = DateComponents()
firstDateComponents.year = 2017
firstDateComponents.month = 1
firstDateComponents.day = 1
firstDateComponents.hour = 23
firstDateComponents.minute = 50
let firstDate = userCalendar.date(from: firstDateComponents)

var secondDateComponents = DateComponents()
secondDateComponents.year = 2016
secondDateComponents.month = 12
secondDateComponents.day = 24
secondDateComponents.hour = 23
secondDateComponents.minute = 55
let secondDate = userCalendar.date(from: secondDateComponents)

var thirdDateComponents = DateComponents()
thirdDateComponents.year = 2017
thirdDateComponents.month = 3
thirdDateComponents.day = 1
thirdDateComponents.hour = 0
thirdDateComponents.minute = 30
let thirdDate = userCalendar.date(from: thirdDateComponents)

var fourthDateComponents = DateComponents()
fourthDateComponents.year = 2017
fourthDateComponents.month = 3
fourthDateComponents.day = 1
fourthDateComponents.hour = 4
fourthDateComponents.minute = 20
let fourthDate = userCalendar.date(from: fourthDateComponents)

var currentDateComponents = DateComponents()
currentDateComponents.year = 2017
currentDateComponents.month = 3
currentDateComponents.day = 2
currentDateComponents.hour = 0
currentDateComponents.minute = 10

let currentDate = userCalendar.date(from: currentDateComponents)
let dates = [firstDate, secondDate, thirdDate, fourthDate]

此示例的预期结果是包含(12:30 AM)的数据结构,即第三个日期。

EDIT3: 试图找到解决方案:

获取时间组件并剥离不相关的日期信息:

let dateComponentsFromDates = dates.map { date -> DateComponents in
    let dateComponents = DateComponents(calendar: userCalendar, timeZone: nil, era: nil, year: nil, month: nil, day: nil, hour: userCalendar.component(.hour, from: date!), minute: userCalendar.component(.minute, from: date!), second: nil, nanosecond: nil, weekday: nil, weekdayOrdinal: nil, quarter: nil, weekOfMonth: nil, weekOfYear: nil, yearForWeekOfYear: nil)
    return dateComponents
}

2 个答案:

答案 0 :(得分:1)

您可以根据日期与当前时间的偏差对日期列表进行排序,使用日历和日期组件,我们可以确保只查看日期的小时和分钟组成部分:

var dates = [Date]()
// assume somehow this array is populated
let cal = Calendar.current
let nowComponents = cal.dateComponents([Calendar.Component.hour, Calendar.Component.minute], from: Date())
let nowMinsIntoDay = (nowComponents.hour ?? 0) * 60 + (nowComponents.minute ?? 0)
// Create a new list of tuples including the date and the minutes from now
let datesWithMinsFromNow = dates.map { (date) -> (Date, Int) in
    let comp = cal.dateComponents([Calendar.Component.hour, Calendar.Component.minute], from: date)
    let minsFromNow = (comp.hour ?? 0) * 60 + (comp.minute ?? 0) - nowMinsIntoDay
    return (date, minsFromNow)
}
// Filter out any pairs that are earlier in the day than now
let datesLaterThanNow = datesWithMinsFromNow.filter { return $0.1 >= 0 }
// Sort the remaining items
let sortedDates = datesLaterThanNow.sorted { $0.1 < $1.1 }
// Take the first item
let closest = sortedDates.first?.0 // closest should now be a `Date` object

答案 1 :(得分:0)

您可以将当前时间转换为毫秒,并检查每个日期是否其毫秒数接近当前时间的毫秒数。

多数民众赞成我会怎么做:

let dates = [Date]()
let currentDate = Date()
var closestMiliseconds = nowDate.currentTimeInMiliseconds()
for date in dates {
    if currentDate.currentTimeInMiliseconds() - date.currentTimeInMiliseconds() < closestMiliseconds {
        closestMiliseconds = Int(date.currentTimeInMiliseconds())
    }
}

let closestDate = closestMiliseconds.dateFromMilliseconds()

这是currentTimeInMiliseconds()函数:

func currentTimeInMiliseconds() -> Int64 {
   let since1970 = self.timeIntervalSince1970
   return Int64(since1970 * 1000)
} 

那就是dateFromMilliseconds()函数:

 func dateFromMilliseconds() -> Date {
   return Date(timeIntervalSince1970: TimeInterval(self)/1000)
 }