Home > Blockchain >  Getting correct date from FSCalendar
Getting correct date from FSCalendar

Time:03-26

I have been looking around a lot but found no real solution to this one.

I use FSCalendar and didSelectDate is giving the wrong date.

The only fix for this that I've found is using this code that I'm using right now:

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

This means if I choose the 22th in February I get "2022/02/22 - 00:00:00", here is the issue, I get the correct day but not time. And in my app I need the correct time as well. Is there anyway I can fix this? Maybe with CalendarComponents for time from Date()?

CodePudding user response:

You'll need to compose the date from FSCalendar and the current datetime to make a new Date. One way to do this:

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(.minute, from: now),
                                      of: date)!

    currentDateVc = newDate
}

Side note: It's better to use features of the calendar/datetime library to get your local time instead of adding seconds from GMT to your date time data. You'll avoid mysterious errors in the future.

  • Related