gpt4 book ai didi

date - swift 3获取最近的小时区列表

转载 作者:行者123 更新时间:2023-12-04 00:36:08 26 4
gpt4 key购买 nike

好的,我在 Swift 3 中有 let date = Date(),我需要获取最近的小时区列表。

假设当前日期是 2017-02-08 15:24:56 +0000,那么所需的列表将是

2017-02-08 15:30:00 +0000
2017-02-08 15:45:00 +0000
2017-02-08 16:00:00 +0000

我怎样才能得到那个日期列表?

编辑 1 2/8/2017 下午 5:54

这是我刚刚尝试做的事情,看起来它得到了我需要的结果。

    let currentDate = Date()
var minute = Calendar.current.component(.minute, from: currentDate)

if minute < 15 {
minute = 15
} else if minute < 30 {
minute = 30
} else if minute < 45 {
minute = 45
} else {
minute = 0
}

var hourQuarterDate = Calendar.current.nextDate(after: currentDate, matching: DateComponents(minute: minute), matchingPolicy: .strict, repeatedTimePolicy: .first, direction: .forward)!

var hourQuarters = [Date]()
hourQuarters.append(hourQuarterDate)

for _ in 1...10 {
hourQuarterDate = Calendar.current.date(byAdding: .minute, value: 15, to: hourQuarterDate)!
hourQuarters.append(hourQuarterDate)
}

最佳答案

您的编辑很有帮助。这是我基于它实现的一个细微变化。

我的主要步骤是将当前日期四舍五入到最近一刻钟:

// Parameters
let minuteGranuity = 15
let numberOfDates = 4

// Find current date and date components
let now = Date()
//2017-03-06 13:23:40 +0000
let calendar = Calendar.current
let hour = calendar.component(.hour, from: now)
let minute = calendar.component(.minute, from: now)

// Round down to nearest date:
let floorMinute = minute - (minute % minuteGranuity)
let floorDate = calendar.date(bySettingHour: hour,
minute: floorMinute,
second: 0,
of: now)!

在您的编辑中,我使用“date(byAdding:”方法将 15 分钟间隔添加到该基准日期:

var dates: [Date] = []
for minutes in stride(from: minuteGranuity, through: minuteGranuity*numberOfDates, by: minuteGranuity) {
let newDate = calendar.date(byAdding: .minute, value: minutes, to: floorDate)!
dates.append(newDate)
}

for date in dates {
print(date)
}

// 2017-03-06 13:30:00 +0000
// 2017-03-06 13:45:00 +0000
// 2017-03-06 14:00:00 +0000
// 2017-03-06 14:15:00 +0000

关于date - swift 3获取最近的小时区列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42117209/

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