Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Sleep Samples sum off by 2 minutes

Hi everyone!

I'm trying to get the total sleep time for a given day, but users report that there's a difference between what my app reports and what the Apple Health app reports. In particular, we're off by 2 minutes less on average.

What we're doing is:

  1. Get all the samples that are either core, deep, rem or unspecified
  2. Cut-off time at 3 PM previous day
  3. Merge overlapping intervals
  4. Add all the remaining intervals

For debugging purposes I'm storing and sending all the raw samples to a server, and I have run tests and I don't find anything wrong. It looks like the number we come up with is correct according to our own rules. I wonder, how is Apple adding up all the samples to arrive at a number that's slightly off to our number.

Any insight would be appreciated. Thanks.

I am not at the position to comment how Health.app does the statistics, but the way you described is about right, that is, fetching all the asleep samples and adding the duration of the samples without counting any overlaps.

The cut-off time is interesting to me though. Did you try to set up a sleep schedule, and use the schedule as the cut-off time to see if that makes any difference?

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Hi, thanks for your answer.

What do you mean by "set up a sleep schedule"? Do you mean in Apple's Health application? And then that I use that schedule for the cutoff time in my code? Because I understand we can't retrieve the schedule using HealthKit, so I guess that wouldn't work for the general case. Right?

Thanks!

Yeah, I mean that you use the built-in Health.app to set up a sleep schedule, and then use the schedule to query the asleep samples.

Your are right that there is no API for retrieving the schedule from HealthKit today, but you can consider providing a UI for users to input, if needed.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Ok thanks, I'll try that then.

A “sleep day” runs from 6pm-6pm so some “naps” between 3pm and 6pm could perhaps help contribute to some differences between what’s reported in Health.

Sleep Samples sum off by 2 minutes
 
 
Q