首页 文章

同一天......但不同?也许时区混乱

提问于
浏览
0

My problem 是我将日期保存到字符串中并作为CoreData中的日期 . 后来,我需要从字符串中提取日期,比较两者,并发现它们是时区问题,但我无法弄清楚如何解决它 .

The Origin of the Dates

我有一个日期选择器的日期,我保存到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),因为这可能对另一个位置的用户不起作用 .

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

1 回答

  • 0

    显而易见,使用userInfo作为@Paulw11建议:

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

相关问题