简体   繁体   中英

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. The data is read in like this:

js对象

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.

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. I won't cover JSON parsing here because there are many, many tutorials and blog posts on that topic. 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). For example, if you have the values as strings, you can use DateFormatter to parse the strings into Date objects.

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. Convert that to hours by dividing by 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

endDate.hours(since: startDate)

instead of timeInterval

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM