【发布时间】:2020-05-23 17:44:05
【问题描述】:
我正在尝试计算特定时间相当于一天的比例。例如,06:00 是 0.25,18:00 是 0.75 等等。
我正在评估一系列 Date 类型的日期,这些日期是在 timeZone = "GMT" 中创建的。下面的例程工作正常。但是,当我为 DST 中的日期评估 23:00 之后的时间时,计算会出错,因为时间被评估为第二天(例如 23:08 被评估为 00:08)
我有什么方法可以识别从 GMT 到 DST 的日期何时进入第二天?然后我可以相应地调整计算。
我的判断输入时间代表比例的函数是:
func getTimeAsProportionOfDay(time: Date) -> Double {
//calculates the amount of day, between 0 and 1 given the input date
let calendar = Calendar.current
let hours = calendar.component(.hour, from: time)
let minutes = calendar.component(.minute, from: time)
let seconds = calendar.component(.second, from: time)
let totalSeconds = Double(hours * 60 * 60 + minutes * 60 + seconds)
return Double(totalSeconds) / Double(secondsInDay)
}
另外,我知道我的 secondsInDay (= 24*60*60) 常数在技术上可能不正确,但我不确定用什么系统常数替换它。
谢谢。
【问题讨论】:
-
有些日子只有 23 小时。你对这些有什么计划?
-
我想确定的是,你是追求字面的真实还是数字的简单。
-
马特,23 小时的日子(幸运的是)自己解决了。关于你的第二点,我认为,就像在任何一天一样,如果我要评估的时间超出了那一天,那么它应该被忽略,因为比例 > 1。但是,我找不到办法排除这些天或评估为 > 1 然后忽略。