时间计算和持续时间

时间:2018-05-05 18:12:45

标签: swift

func timeDuration() {
        let currentTimeStr = myTime()
        let oldTimeStr = UserDefaults.standard.string(forKey: "myTime")

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "H:mm:ss"

        let dateComponentFormatter = DateComponentsFormatter()
        dateComponentFormatter.allowedUnits = [.hour, .minute]
        dateComponentFormatter.unitsStyle = .short

        if let currentTime = dateFormatter.date(from: currentTimeStr),
            let oldTime = dateFormatter.date(from: oldTimeStr!),
            let durationStr = dateComponentFormatter.string(from: oldTime, to: currentTime)
        {
            print(durationStr) // 2 hrs
            lblDuration.stringValue = durationStr + " Ago"            }

    }
func myTime()  -> String {
    let date = Date()
    let calendar = Calendar.current
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)



    return "\(hour):\(minutes):\(seconds)"
}

我在我的应用程序中使用这两个功能,基本上我的应用程序记录了我最后一次服用一剂药物。它还调用timeDuration函数,因此我可以显示自上次剂量以来的小时数和分钟数。它在上午12点有一个错误,它首先显示时间为0.00.00所以有些它如何弄乱持续时间。我提供了这个屏幕截图。此外,我已经尝试添加if语句,如果小时== 0然后将小时更改为24,它显示时间为24:00:00但它仍然影响我的持续时间代码。谁能帮忙。 enter image description here

enter image description here

您可以在下面的链接下载我的项目的源代码。 Source Code Of Project

1 个答案:

答案 0 :(得分:0)

您可以将时间存储为TimeInterval,存储为Double

    let timeOfDose = Date().timeIntervalSince1970
    UserDefaults.standard.set(timeOfDose, forKey: "LastDose")

实施将TimeInterval转换为String

的功能
    func stringFromTimeInterval(timeInterval: TimeInterval) -> NSString {

        let timeIntervalInt = Int(timeInterval)

        let hours = (timeIntervalInt / 3600)
        let minutes = (timeIntervalInt / 60) % 60
        let seconds = timeIntervalInt % 60

        return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds)
    }

然后您可以使用以下方法实现:

    //Get current date/time as TimeInterval (Double)
    let currentTimeInterval = Date().timeIntervalSince1970

    //Get date/time of last dose as TimeInterval (Double)
    let lastDoseTimeInterval = UserDefaults.standard.double(forKey: "LastDose")

    //Get the difference
    let durationTimeInterval = currentTimeInterval - lastDoseTimeInterval

    //convert lastDoseTimeInterval to Date Object
    let lastDoseDate = Date(timeIntervalSince1970: lastDoseTimeInterval)

    //Initialise Date Formatter
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm"

    //Create your output Strings
    let currentTimeString = dateFormatter.string(from: Date()) //eg 19:40
    let lastDoseString = dateFormatter.string(from: lastDoseDate) //eg 19:32
    let durationString = stringFromTimeInterval(timeInterval: durationTimeInterval) //eg 00:07:47