Home > Enterprise >  How to calculate sleep hours with Healthkit
How to calculate sleep hours with Healthkit

Time:12-08

I'm trying to create a graph with the sleep hours, I get the data from HealthKit but I'm not sure on how to make the math, I receive the SleepData like this:

>>>>>>> SLEEP [{"endDate": "2021-12-07T09:07:00.000-0300", "sourceId": "com.apple.Health", "sourceName": "Health", "startDate": "2021-12-06T22:07:00.000-0300", "value": "INBED"}]

I use moment in my application to get some dates, but I'm not sure how to do the math to get the time between startDate and end Date

the code to get this info is the healthKit standard

AppleHealthKit.getSleepSamples(options, (callbackError, results) => {
        setSleepAnalysis(results);
        console.log('>>>>>>> SLEEP', results);

Thanks for your help

CodePudding user response:

If you want it in seconds:

function getMinutesBetweenDates(startDate, endDate) {
    var diff = endDate.getTime() - startDate.getTime();
    return (diff / 60000);
}

const start = Date.parse(yourStartDate);
const end = Date.parse(yourEndDate);

getMinutesBetweenDates(start, end); <== your result
  • Related