简体   繁体   中英

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)
      })
  }
}

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

let calendar = Calendar.current

Try manually setting the time zone for the DateComponents before converting them into a Date :

let calendar = Calendar.current
var dateComponents = summary.dateComponents(in: calendar)
dateComponents.timeZone = calendar.timeZone
let date = dateComponents.date!

The DateComponents associated with each HKActivitySummary do not include a time zone. The resulting Date may be slightly off from what you're expecting because it's not in the correct time zone (Swift defaults to UTC if a time zone is not specified). Manually specifying the time zone should resolve this issue.

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