相同的日期...但不同?也许时区混乱

Same Date... But Different? Maybe timezone confusion

我的问题 是我将日期保存到字符串中并作为日期保存在 CoreData 中。稍后,我需要从字符串中提取日期,比较两者,发现它们是相同的日期。现在,平等检查失败了。这两个日期相隔 7 小时,但分钟正确。我认为这是一个时区问题,但我不知道如何解决它。

枣的由来

我有一个日期选择器的日期,我这样保存到 CoreData:

task.setValue(dueDatePicker.date, forKey: "dueDate")

之后我格式化日期并将该日期插入到消息中:

let dateFormatter = DateFormatter()
let dateFormat = DateFormatter.Style.medium
let timeFormat = DateFormatter.Style.short
dateFormatter.dateStyle = dateFormat     
dateFormatter.timeStyle = timeFormat
let formattedDate = dateFormatter.string(from: date)
let message = ("Upcoming task on \(formattedDate)")

该消息成为通知的一部分。几小时或几天后(当通知触发并且用户选择了一个操作时)我得到了 CoreData 日期:

fetchRequest.predicate = NSPredicate(format: "dueDate = %@", dateOfTask)

然后我分解通知消息并得到日期:

let start = notifString.range(of: "on ")
let rawDate = notifString[(start.upperBound)!..<(notifString.endIndex)]
let dateFormatter = DateFormatter()
dateFormatter.timeZone =
dateFormatter.dateFormat = "MMM-d-yyyy, H:mm a"
let dateFromString = dateFormatter.date(from: rawDate)

最后,我比较一下。目前时间显然是同一天和同一分钟,但时区相差约 7 小时。但是,我不想只强制匹配一个时区(例如强制使用 UTC),因为这可能不适用于其他位置的用户。

如何在不出现这个明显的时区问题的情况下检索两个日期?

很明显,按照@Paulw11 的建议使用 userInfo:

    newLocalNotif.fireDate = dueDateWarningTime
    newLocalNotif.alertBody = message
    newLocalNotif.timeZone = TimeZone.autoupdatingCurrent
    newLocalNotif.soundName = UILocalNotificationDefaultSoundName
    newLocalNotif.category = "DueDates"
    newLocalNotif.userInfo = ["name": name, "desc": desc, "dueDate" : date]