Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HKActivitySummary dateComponents a day behind

For some strange reason when executing a HKActivitySummaryQuery the returned date component for each summary is a day behind. The query returns data from the correct date but the dateComponents date of the data is behind by a day. I've tried setting the timezone and locale but results remain the same.

Summary Model

struct ActivitySummary {
  init?(_ summary: HKActivitySummary) {
    var calendar = Calendar.current
    calendar.timeZone = TimeZone.current
    guard let date =  summary.dateComponents(for: calendar).date else { return nil }

    print("ORIGINAL: ", date.description(with: Locale.current))
    //Expected: Tuesday, January 30, 2018 at 7:00:00 PM Eastern Standard Time
    //Results: Monday, January 29, 2018 at 7:00:00 PM Eastern Standard Time

    let other = calendar.dateComponents( [ .year, .month, .day ], from: date)
    print("START OF DAY: ", date.startOfDay.description(with: Locale.current)) 
    //Expected: Tuesday, January 30, 2018 at 12:00:00 AM Eastern Standard Time
    //Results: Monday, January 29, 2018 at 12:00:00 AM Eastern Standard Time
  }
}


HKAcitivitySummaryQuery

func summaryQuery(){
    let predicate = HKQuery.predicate(forActivitySummariesBetweenStart: fromDate.components(), end: toDate!.components())
   let query = HKActivitySummaryQuery(predicate: predicate) { (query, summaries, error) in
      guard let summaries = summaries, summaries.count > 0 else {
          return
      }
    // 
    var activitySummaries: [ActivitySummary] = []
    activitySummaries = summaries.compactMap({
        ActivitySummary($0)
      })
  }
}
like image 578
kye Avatar asked Nov 08 '22 11:11

kye


1 Answers

Maybe the calendar you're working with is wrong. set your calendar like this :

let calendar = Calendar.current
like image 106
tara tandel Avatar answered Nov 15 '22 05:11

tara tandel