简体   繁体   中英

How can I find the next weekend Swift

I have an app in which I want to show some data when it's Saturday or Sunday. Actually I have a segmented control and if I press one of my option (which will be the weekend) I want to check If it is Saturday or Sunday but only the first weekend.

This is what I've done for my first option in segmented control to take the current date

dateevent is a variable that I take to check if is the currentDate currentDate is declared to be the currentDate

  if  dateevent.earlierDate(self.currentDate).isEqualToDate(self.currentDate){

  if NSCalendar.currentCalendar().isDate(dateevent, equalToDate: self.currentDate, toUnitGranularity: .Day){

                                //Do something
                            }

                        }

First find the number of days to add to NSDateComponents weekday property and then You can use dateByAddingComponents(_:toDate:options:) .

let today = NSDate()
let calendar = NSCalendar.currentCalendar()

let todayWeekday = calendar.component(.Weekday, fromDate: today)

let addWeekdays = 7 - todayWeekday  // 7: Saturday number
var components = NSDateComponents()
components.weekday = addWeekdays

let nextSaturday = calendar.dateByAddingComponents(components, toDate: today, options: .MatchFirst)

From the Apple docs :

If the date does fall within a weekend, you can use the rangeOfWeekendStartDate:interval:containingDate: method to determine the start date of that weekend period. Otherwise, you can use the nextWeekendStartDate:interval:options:afterDate: method to determine the start date of the next or previous weekend.

extension for getting day of the week

func dayOfTheWeek() -> String? {
    let dateFormatter = NSDateFormatter()
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
    dateFormatter.dateFormat = "EEEE"
    return dateFormatter.stringFromDate(self)
}

then you can just count how many days do yo need to weekend and add it to NSDate

NSDate().dateByAddingTimeInterval(60 * 60 * 24 * daysFromTodayToWeekend)

Swift 4 Solution

I have figured out according to my requirement, where I have find out dates for following.

1. Today

2. Tomorrow 

3. This Week 

4. This Weekend 

5. Next Week 

6. Next Weekend

So, I have created Date Extension to get Dates of Current Week and Next Week .

CODE

extension Date {

    func getWeekDates() -> (thisWeek:[Date],nextWeek:[Date]) {
        var tuple: (thisWeek:[Date],nextWeek:[Date])
        var arrThisWeek: [Date] = []
        for i in 0..<7 {
            arrThisWeek.append(Calendar.current.date(byAdding: .day, value: i, to: startOfWeek)!)
        }
        var arrNextWeek: [Date] = []
        for i in 1...7 {
            arrNextWeek.append(Calendar.current.date(byAdding: .day, value: i, to: arrThisWeek.last!)!)
        }
        tuple = (thisWeek: arrThisWeek,nextWeek: arrNextWeek)
        return tuple
    }

    var tomorrow: Date {
        return Calendar.current.date(byAdding: .day, value: 1, to: noon)!
    }
    var noon: Date {
        return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
    }

    var startOfWeek: Date {
        let gregorian = Calendar(identifier: .gregorian)
        let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
        return gregorian.date(byAdding: .day, value: 1, to: sunday!)!
    }

    func toDate(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

USAGE:

let arrWeekDates = Date().getWeekDates() // Get dates of Current and Next week.
let dateFormat = "MMM dd" // Date format
let thisMon = arrWeekDates.thisWeek.first!.toDate(format: dateFormat)
let thisSat = arrWeekDates.thisWeek[arrWeekDates.thisWeek.count - 2].toDate(format: dateFormat)
let thisSun = arrWeekDates.thisWeek[arrWeekDates.thisWeek.count - 1].toDate(format: dateFormat)

let nextMon = arrWeekDates.nextWeek.first!.toDate(format: dateFormat)
let nextSat = arrWeekDates.nextWeek[arrWeekDates.nextWeek.count - 2].toDate(format: dateFormat)
let nextSun = arrWeekDates.nextWeek[arrWeekDates.nextWeek.count - 1].toDate(format: dateFormat)

print("Today: \(Date().toDate(format: dateFormat))") // Sep 26
print("Tomorrow: \(Date().tomorrow.toDate(format: dateFormat))") // Sep 27
print("This Week: \(thisMon) - \(thisSun)") // Sep 24 - Sep 30
print("This Weekend: \(thisSat) - \(thisSun)") // Sep 29 - Sep 30
print("Next Week: \(nextMon) - \(nextSun)") // Oct 01 - Oct 07
print("Next Weekend: \(nextSat) - \(nextSun)") // Oct 06 - Oct 07

You can modify Extension according to your need.

Thanks!

I use this implementation to get the next Saturday at specific time:

CODE (Swift 5):

func nextSaturday(atHour hour: Int, min: Int) -> Date {
    let today = Date()
    let daysToAdd = 7 - (Calendar.current.dateComponents([.weekday], from: today).weekday ?? 0 )
    let nextSaturday = Calendar.current.date(byAdding: .day, value: daysToAdd, to: today)!
    return Calendar.current.date(bySettingHour: hour, minute: min, second: 0, of: nextSaturday)!
}

How to use it:

nextSaturday(atHour: 10, min: 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM