So, I have a weird problem going on. I've been testing an app that fetches the user's birth date from the Health app. But it turns out that, when converted to a Date
object, I've noticed that the date is wrong. It goes back one day. But only in my iPhone. In the simulator it works okay. The simulator is for iOS 16 and my iPhone is on iOS 15. The XCode version is 14.3.1 and I'm on SwiftUI.
By analysing the object, it looks like the date is going back to 23 hours of the previous day. I suspect it's related to my timezone, because I am in the UK, and at winter time we are on GMT (UTC+0) and at summer we are on BST (UTC+1).
Can someone confirm this is the case?
I have been trying to ignore the timezone entirely, but I had no success. It keeps giving me the wrong day. Can someone suggest a clean solution for this issue? My current code is below. Thanks!
if let birthday = try? healthStore.dateOfBirthComponents() {
var calendar = Calendar.current
calendar.timeZone = TimeZone.current
// TimeZone(secondsFromGMT: 0)! <- This works, but I don't want to assume the timezone for all users.
// I've tried omitting the timezone line as well, but it doesn't work.
let dateComponents = DateComponents(
calendar: calendar,
year: birthday.year,
month: birthday.month,
day: birthday.day
)
let date = calendar.date(from: dateComponents)
print("result was \(String(describing: date))")
print(birthday)
} else {
print("Error fetching birthday")
}