How to get Monday's date of the current week in swift

I’m trying to get Monday’s date of the current week. This is treated as the first day of the week in my table view.
I also need to get Sunday’s of the current week. This is treated as the last day of the week in my table view.

Current attempt:

  • iOS 8 - get current date as DD/MM/YYYY
  • Date to milliseconds and back to date in Swift
  • Comparing dates
  • Swift - check if a timestamp is yesterday, today, tomorrow, or X days ago
  • Comparing time and date in objective C
  • How to get the 'n' weekday of a Date
  • let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    calendar.firstWeekday = 1
    //attempt to changefirstday
    
    let dateFormatter = NSDateFormatter()
    let theDateFormat = NSDateFormatterStyle.ShortStyle
    let theTimeFormat = NSDateFormatterStyle.ShortStyle
    dateFormatter.dateStyle = theDateFormat
    dateFormatter.timeStyle = theTimeFormat
    
    let currentDateComponents = calendar.components([.YearForWeekOfYear, .WeekOfYear ], fromDate: date)
    let startOfWeek = calendar.dateFromComponents(currentDateComponents)
    print("startOfWeek is \(startOfWeek)")
    let stringDate = dateFormatter.stringFromDate(startOfWeek!)
    print("string date is \(stringDate)") //This is returning Sunday's date
    

    5 Solutions Collect From Internet About “How to get Monday's date of the current week in swift”

    Here is a simple function that will give you this week’s Monday’s date,

    func getWeekDaysInEnglish() -> [String] {
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        calendar.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        return calendar.weekdaySymbols
    }
    
    enum SearchDirection {
        case Next
        case Previous
    
        var calendarOptions: NSCalendarOptions {
            switch self {
                case .Next:
                    return .MatchNextTime
                case .Previous:
                    return [.SearchBackwards, .MatchNextTime]
            }
        }
    }
    
    func get(direction: SearchDirection, _ dayName: String, considerToday consider: Bool = false) -> NSDate {
        let weekdaysName = getWeekDaysInEnglish()
    
        assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)")
    
        let nextWeekDayIndex = weekdaysName.indexOf(dayName)! + 1 // weekday is in form 1 ... 7 where as index is 0 ... 6
    
        let today = NSDate()
    
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    
        if consider && calendar.component(.Weekday, fromDate: today) == nextWeekDayIndex {
            return today
        }
    
        let nextDateComponent = NSDateComponents()
        nextDateComponent.weekday = nextWeekDayIndex
    
    
        let date = calendar.nextDateAfterDate(today, matchingComponents: nextDateComponent, options: direction.calendarOptions)
        return date!
    }
    
    get(.Next, "Monday") // Nov 2, 2015, 12:00 AM
    get(.Next, "Sunday") // Nov 1, 2015, 12:00 AM
    
    get(.Previous, "Sunday") // Oct 25, 2015, 12:00 AM
    get(.Previous, "Monday") // Oct 26, 2015, 12:00 AM
    
    get(.Previous, "Thursday") // Oct 22, 2015, 12:00 AM
    get(.Next, "Thursday") // Nov 5, 2015, 12:00 AM
    get(.Previous, "Thursday", considerToday:  true) // // Oct 29, 2015, 12:00 AM
    

    You can use this method to get any days and day name you provide to the function should be either of these,

    "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    

    You can use calendar ISO8601 where the first weekday is monday

    var mondaysDate: NSDate {
        let iso8601 =  NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
        return iso8601.dateFromComponents(iso8601.components([.YearForWeekOfYear, .WeekOfYear], fromDate: NSDate()))!
    }
    
    print(mondaysDate.descriptionWithLocale(NSLocale.currentLocale()))  // "Monday, October 26, 2015 at 12:00:00 AM Brasilia Summer Time"
    

    Swift 3 or later

    var mondaysDate: Date {
        return Calendar(identifier: .iso8601).date(from: Calendar(identifier: .iso8601).dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date()))!
    }
    
    print(mondaysDate.description(with: .current))   // "Monday, November 7, 2016 at 12:00:00 AM Brasilia Summer Time\n"
    

    Here is the extension I created, first it finds sunday and then it adds one day

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

    Try to use:

    calendar.firstWeekday = 2
    

    Edit

    To be more specific: NSCalendar.currentCalendar() returns user calendar. According to docs:

    The returned calendar is formed from the settings for the current user’s chosen system locale overlaid with any custom settings the user has specified in System Preferences.

    If you want always Monday as first day, I think you should use:

    let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    calendar!.firstWeekday = 2
    

    Addition to @Saneep answer

    If you would like to get exact dateTime as per given/current date (lets say you wanted to convert Monday’s dateTime -> 23-05-2016 12:00:00 to 23-05-2016 05:35:17) then try this:

    func convertDate(date: NSDate, toGivendate: NSDate) -> NSDate {
        let calendar = NSCalendar.currentCalendar()
        let comp = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: toGivendate)
        let hour = comp.hour
        let minute = comp.minute
        let second = comp.second
    
        let dateComp = calendar.components([.Year, .Month, .Day], fromDate: date)
        let year = dateComp.year
        let month = dateComp.month
        let day = dateComp.day
    
        let components = NSDateComponents()
        components.year = year
        components.month = month
        components.day = day
        components.hour = hour
        components.minute = minute
        components.second = second
    
        let newConvertedDate = calendar.dateFromComponents(components)
    
        return newConvertedDate!
    }