从 FSCalendar 获取正确的日期

Getting correct date from FSCalendar

我找了很多地方,但没有找到真正的解决方案。

我使用 FSCalendar 并且 didSelectDate 给出了错误的日期。

我发现的唯一解决方法是使用我现在正在使用的代码:

func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {        
    let newDate = date.addingTimeInterval(TimeInterval(TimeZone.current.secondsFromGMT(for: date)))
        currentDateVc = newDate
    }

这意味着如果我选择 2 月 22 日 ,我会得到 "2022/02/22 - 00:00:00",这就是问题所在,我得到的是正确的日期,但不是时间。在我的应用程序中,我也需要正确的时间。无论如何我可以解决这个问题吗?也许 CalendarComponents 时间从 Date()?

您需要将 FSCalendar 的日期和当前 datetime 的日期组成一个新的 Date。一种方法:

func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
    let now = Date()
    let cal = Calendar.current

    let newDate = cal.date(bySettingHour: cal.component(.hour, from: now),
                                  minute: cal.component(.minute, from: now),
                                  second: cal.component(.second, from: now),
                                      of: date)!

    currentDateVc = newDate
}

旁注:最好使用 calendar/datetime 库的功能来获取当地时间,而不是将 GMT 秒数添加到日期中时间数据。您将避免以后出现神秘错误。