ios - 如何在swift 4中跳过精确的小时和分钟时间的四舍五入
问题描述
我在 swift 4 中工作,我有一个场景是将时间四舍五入到最近的 5 分钟(如上午 11:12 - 上午 11:15)。对于提到的这种情况,我可以做到这一点。但在这里我的问题是我不应该在“上午 11:15”的时候结束。谁能帮我解决这个问题。在此先感谢。请找到我的以下代码..
func getTimesData{
let date = Date()
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
let dateString = df.string(from: date)
let convertedDate = dateString.convertingStringToDate(date: dateString)
let roundedDate = convertedDate.rounded(minutes: 5, rounding: .ceil) //Here I am rounding the time.
let dateAdded = roundedDate.addingTimeInterval(5 * 180)
}
下面的代码是我从 StackOverFlow 本身获得的时间。
enum DateRoundingType {
case round
case ceil
case floor
}
extension Date {
func rounded(minutes: TimeInterval, rounding: DateRoundingType = .round) -> Date {
return rounded(seconds: minutes * 60, rounding: rounding)
}
func rounded(seconds: TimeInterval, rounding: DateRoundingType = .round) -> Date {
var roundedInterval: TimeInterval = 0
switch rounding {
case .round:
roundedInterval = (timeIntervalSinceReferenceDate / seconds).rounded() * seconds
case .ceil:
roundedInterval = ceil(timeIntervalSinceReferenceDate / seconds) * seconds
case .floor:
roundedInterval = floor(timeIntervalSinceReferenceDate / seconds) * seconds
}
return Date(timeIntervalSinceReferenceDate: roundedInterval)
}
}
解决方案
无需先使用 DateFormatter 来“烘焙”日期,而是直接调用舍入函数。
let rounded = Date().rounded(minutes: 5, rounding: .ceil)
如果您对 11:15 没有四舍五入到 11:15 有疑问,那可能是因为秒数不完全为 0,所以我建议改用默认值.round
。
let rounded = Date().rounded(minutes: 5)
推荐阅读
- wmi - 如何使用 WMI 查询获取多个 rras sstp 端口?
- excel - 复制/粘贴图表
- java - XML 与 Base64 编码字符串到 PDF
- android - 如何防止用户从文件资源管理器中选择 jpeg 或 png 类型
- python - Keras 自定义指标 R2 与 SKlearn R2
- sql - 如何使用 BigQuery UNNEST 在单行而不是多行中查看每个结构及其值?
- kibana - Lucene查询语言和KQL有什么区别
- opencv - 如何通过在python中使用pytesseract和opencv-python来识别其他更大对象下的变形文本?
- javascript - 焦点/模糊事件未触发
- splunk - 如何提取splunk字段中最后一个斜杠后的内容?