[英]Get the length between two dates in hours
I am reading sleep data into my react-native app using react-native-healthkit
, and I need to find a way to get the total amount of sleep time.我正在使用
react-native-healthkit
睡眠数据读取到我的 react-native 应用程序中,我需要找到一种方法来获取总睡眠时间。 The data is read in like this:数据是这样读入的:
If anyone has any ideas on the best way to handle this data, please let me know.如果有人对处理这些数据的最佳方式有任何想法,请告诉我。
extension Date {
/// Hours since current date to given date
/// - Parameter date: the date
func hours(since date: Date) -> Int {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.hour], from: self, to: date)
return dateComponents.month ?? 0
}
}
date2.hours(since: date1)
Using .timeIntervalSince
is a bad practice, because some hours may be shorter than other.使用
.timeIntervalSince
是一种不好的做法,因为有些小时可能比其他小时短。
If anyone has any ideas on the best way to handle this data please let me know.
如果有人对处理这些数据的最佳方式有任何想法,请告诉我。
It really depends on how you're parsing that JSON data.这实际上取决于您如何解析 JSON 数据。 I won't cover JSON parsing here because there are many, many tutorials and blog posts on that topic.
我不会在这里介绍 JSON 解析,因为有很多关于该主题的教程和博客文章。 Here's one in case you're not sure where to start.
如果您不确定从哪里开始, 这里有一个。
Your goal is to end up with date objects ( Date
in Swift, NSDate
in Objective-C).你的目标是得到日期对象(Swift 中的
Date
,Objective-C 中的NSDate
)。 For example, if you have the values as strings, you can use DateFormatter
to parse the strings into Date
objects.例如,如果您将值作为字符串,则可以使用
DateFormatter
将字符串解析为Date
对象。
Once you have those date objects you can use the operations that those objects supply to get a TimeInterval
, which is a double
representing an interval in seconds.拥有这些日期对象后,您可以使用这些对象提供的操作来获取
TimeInterval
,它是表示以秒为单位的间隔的double
TimeInterval
。 Convert that to hours by dividing by 3600:通过除以 3600 将其转换为小时:
let interval = endDate.timeIntervalSince(startDate)
let hours = interval / 3600
Try this尝试这个
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
guard let startDate = dateFormatter.date(from: "yourStartDate"),
let endDate = dateFormatter.date(from: "yourEndDate") else {
return
}
let difference = endDate.timeIntervalSince(startDate)
If you are targeting iOS 13 and above you can use如果您的目标是 iOS 13 及更高版本,则可以使用
endDate.hours(since: startDate)
instead of timeInterval而不是时间间隔
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.