If current date is 3 August 2018 (friday), i want to get 4 & 5 august 2018 (saturday and sunday)
if current date is 4 august (saturday), I still want to get 4 & 5 august 2018 (saturday and sunday)
if current date is 6 august (monday) then I want to get 11 & 12 August (saturday and sunday)
how to do that in swift?
Calendar
has convenience methods for that
dateIntervalOfWeekend(containing:start:interval:)
checks if the given date is in a weekend and returns the startDate
and interval
(duration in seconds) in the inout parameters. The Bool
return value is true
if the given date is within a weekend.
nextWeekend(startingAfter:start:interval:)
returns startDate
und interval
in the inout parameters for the upcoming (.forward
parameter) or passed (.backward
) weekend.
let now = Date()
var startDate = Date()
var interval : TimeInterval = 0.0
if !Calendar.current.dateIntervalOfWeekend(containing: now, start: &startDate, interval: &interval) {
Calendar.current.nextWeekend(startingAfter: now, start: &startDate, interval: &interval, direction: .forward)
}
print(startDate, startDate.addingTimeInterval(interval))
If you need start of Saturday and start of Sunday then replace the last line with
let endDate = startDate.addingTimeInterval(interval-1)
print(startDate, Calendar.current.startOfDay(for: endDate))
Alternatively – suggested by Martin R (thanks) – use dateIntervalOfWeekend(containing:)
/ nextWeekend(startingAfter:)
which both return a DateInterval
object containing start
, end
and duration
let now = Date()
let calendar = Calendar.current
let weekEndInterval = calendar.dateIntervalOfWeekend(containing: now) ?? calendar.nextWeekend(startingAfter: now)!
let startDate = weekEndInterval.start
let endDate = startDate.addingTimeInterval(weekEndInterval.duration-1)
print(startDate, calendar.startOfDay(for: endDate))
let (nextSaturday,orderTotal) = getWeekends()
print(nextSaturday)
print(nextSunday)
func getWeekends() -> (Date,Date) {
let today = Date()
let calendar = Calendar.current
let todayWeekday = calendar.component(.weekday, from: today)
let addWeekdays = 7 - todayWeekday
var components = DateComponents()
components.weekday = addWeekdays
let nextSaturday = calendar.date(byAdding: components, to: today)
components.weekday = addWeekdays + 1
let nextSunday = calendar.date(byAdding: components, to: today)
return (nextSaturday,nextSunday)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With