Calendar.Nextdate() Is Acting Really Weird When Using .Backward for Direction. Only for the Last Day of the Month

Calendar.nextDate() is acting really weird when using .backward for direction. Only for the last day of the month

This does appear to be a bug that should be reported to Apple. Be sure you include a runnable test app demonstrating the issue. Note that this bug only appears in iOS. In macOS (at least a macOS playground), the code works as expected.

In the meantime there is a fairly simple workaround.

Change your code to use .forward instead of .backward. This will give the next date instead of the previous date. There does not seem to be any bugs going in that direction. Then use:

Calendar.current.date(byAdding: .day, value: -1, date: result)

to get your desired result by going back one day.

Calculate previous Sunday when DST changed on the previous Sunday

This is likely an Apple bug, as the comment above says.

There is a very ugly workaround by first finding the "next" Sunday, then using that date to find the previous Sunday. I am sure there are some edge cases where this won't work, but maybe it might help you.

// Not recommended for production code

var nextSunday = Calendar.current.nextDate(after: Date(),
matching: DateComponents(weekday: 1),
matchingPolicy: .nextTime,
repeatedTimePolicy: .first,
direction: .forward)!

var lastSunday = Calendar.current.nextDate(after: nextSunday,
matching: DateComponents(weekday: 1),
matchingPolicy: .nextTime,
repeatedTimePolicy: .first,
direction: .backward)!

Sample Image

How Can we swipe only month or day when we click on next or previous button in fscalendar in swift4

You can use this function to switch any date component in FSCalendar 2.8.0 (with Swift 4.2/Xcode 10):

func switchDateComponent(component: Calendar.Component, isNextDirection: Bool) {
if let nextDate = Calendar.current.date(byAdding: component, value: isNextDirection ? 1 : -1, to: calendar.selectedDate ?? Date()) {
calendar.select(nextDate, scrollToDate: true)
}
}

Now if you need to select previous/next day you can call switchDateComponent(component: .day, isNextDirection: false) or switchDateComponent(component: .day, isNextDirection: true). For the month component it will be similar, just call switchDateComponent(component: .month, isNextDirection: false) or switchDateComponent(component: .month, isNextDirection: true).



Related Topics



Leave a reply



Submit