【问题标题】:Adding Time Interval. e.g hours, minutes and seconds添加时间间隔。例如小时、分钟和秒
【发布时间】:2019-12-25 14:43:33
【问题描述】:

我从多个对象的“01:32:34”等小时、分钟和秒的响应中获取时间。我已将其保存在自定义日期对象中,我在其中保存日期值和字符串值,有大量记录,因此我将其保存在本地数据库中,并在检索时以 @ 格式获取日期值987654321@ 而我从响应中获得的字符串值也是19:01:04。现在我想添加所有这些值以返回一个字符串,例如1:15:1600:15:0200:45:27 应该返回 2 小时 15 分 45 秒。我探索了Calendar.Components.byAdding,但那里的方法只允许我添加一个组件,它不接收数组并返回Date。有什么快速的方法来实现这一点,我想通过一种优雅而适当的方法来实现这一点,我可以想到一些修复,但它们似乎不合适。

【问题讨论】:

    标签: swift datetime time calendar swift5


    【解决方案1】:

    我将假设“01:32:34”表示经过的时间为 5,554 秒,而不是凌晨 1:32。所以,我会将其转换为TimeInterval,而不是Date

    func timeInterval(from string: String) -> TimeInterval? {
        let components = string.components(separatedBy: ":").map { Double($0) }
        guard 
            components.count == 3,
            let hours = components[0],
            let minutes = components[1],
            let seconds = components[2]
        else { return nil }
    
        return ((hours * 60) + minutes) * 60 + seconds
    }
    

    您可以选择存储原始的“01:32:34”字符串或此值 5,554.0。

    无论如何,添加这些数字时间间隔是微不足道的。要显示生成的TimeInterval,您可以使用DateComponentsFormatter,例如

    let timeIntervalFormatter: DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .positional
        formatter.allowedUnits = [.hour, .minute, .second]
        return formatter
    }()
    
    func totalElapsed(_ strings: [String]) -> String? {
        let total = strings.reduce(TimeInterval.zero) { sum, string in
            sum + (timeInterval(from: string) ?? 0)
        }
        return timeIntervalFormatter.string(from: total)
    }
    
    let strings = ["1:15:16", "00:15:02", "00:45:27"]
    
    let result = totalElapsed(strings)
    

    02:15:45

    或者,如果您想要更多(本地化)自然语言表示,请使用 unitsStyle of .full

    2 小时 15 分 45 秒

    这种方法(使用TimeInterval,而不是Date)的优点是它还可以表示超过24 小时的时间间隔。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多