计算两个时间字符串"07:35 AM"之间的差.和"09:35 PM"在几个小时内 [英] Calculate the difference between two time strings "07:35 AM" and "09:35 PM" in hours

查看:25
本文介绍了计算两个时间字符串"07:35 AM"之间的差.和"09:35 PM"在几个小时内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击此处查看图片我在两个按钮上都有时间它的标题是我两次与AM/PM在一起.我尝试了很多方法来减去这两个按钮之间的时间,但未成功.请向我建议正确的方法,如如何减去输入时间和输出时间,并仅以小时为单位得出总时数.

Click here to see the imageI am having the times on two button on its title I am having the two time with AM/PM. I have tried so many ways to subtract the times between these two buttons but not successful. Please suggest me the proper way as the how to subtract the IN time and OUT time and get the TOTAL HOUR as a result only in hours.

推荐答案

您可以使用Calendar方法dateComponents计算两个日期之间的小时数.您可以使用DateFormatter从字符串中获取日期:

You can use Calendar method dateComponents to calculate how many hours there is between two dates. You can use DateFormatter to get the dates from your strings:

let start = "09:35 PM"
let end = "09:36 AM"

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "hh:mm a"

if let startDate = dateFormatter.date(from: start),
    let endDate = dateFormatter.date(from: end) {
    let hours = Calendar.current.dateComponents([.hour], from: startDate, to: endDate < startDate ? Calendar.current.date(byAdding: .day, value: 1, to: endDate) ?? endDate : endDate).hour ?? 0
    print(hours)  // 12
}

这篇关于计算两个时间字符串"07:35 AM"之间的差.和"09:35 PM"在几个小时内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆