Search code examples
javascriptiosreact-nativehealthkit

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 object

If anyone has any ideas on the best way to handle this data, please let me know.


Solution

  • 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.