Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get this weekend date in swift? [duplicate]

Tags:

ios

swift

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?

like image 637
sarah Avatar asked Aug 04 '18 04:08

sarah


2 Answers

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))
like image 85
vadian Avatar answered Nov 02 '22 23:11

vadian


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)
    }
like image 43
Tm Goyani Avatar answered Nov 02 '22 23:11

Tm Goyani