How to get the Monday date of the current week in quick

I'm trying to get the current week date on Monday. This is considered the first day of the week in my view of the table. I also need to get Sunday this week. This is considered the last day of the week in my view of the table.

Current attempt:

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 date 
+16
date swift nscalendar
source share
7 answers

I wrote Date extensions to get Date for a specific day of the week, and here is how easy it is to use with Swift 5,

 Date.today() // Oct 15, 2019 at 9:21 AM Date.today().next(.monday) // Oct 21, 2019 at 9:21 AM Date.today().next(.sunday) // Oct 20, 2019 at 9:21 AM Date.today().previous(.sunday) // Oct 13, 2019 at 9:21 AM Date.today().previous(.monday) // Oct 14, 2019 at 9:21 AM Date.today().previous(.thursday) // Oct 10, 2019 at 9:21 AM Date.today().next(.thursday) // Oct 17, 2019 at 9:21 AM Date.today().previous(.thursday, considerToday: true) // Oct 10, 2019 at 9:21 AM Date.today().next(.monday) .next(.sunday) .next(.thursday) // Oct 31, 2019 at 9:21 AM 

And here’s the extension of the date for this,

 extension Date { static func today() -> Date { return Date() } func next(_ weekday: Weekday, considerToday: Bool = false) -> Date { return get(.next, weekday, considerToday: considerToday) } func previous(_ weekday: Weekday, considerToday: Bool = false) -> Date { return get(.previous, weekday, considerToday: considerToday) } func get(_ direction: SearchDirection, _ weekDay: Weekday, considerToday consider: Bool = false) -> Date { let dayName = weekDay.rawValue let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() } assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)") let searchWeekdayIndex = weekdaysName.firstIndex(of: dayName)! + 1 let calendar = Calendar(identifier: .gregorian) if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex { return self } var nextDateComponent = calendar.dateComponents([.hour, .minute, .second], from: self) nextDateComponent.weekday = searchWeekdayIndex let date = calendar.nextDate(after: self, matching: nextDateComponent, matchingPolicy: .nextTime, direction: direction.calendarSearchDirection) return date! } } // MARK: Helper methods extension Date { func getWeekDaysInEnglish() -> [String] { var calendar = Calendar(identifier: .gregorian) calendar.locale = Locale(identifier: "en_US_POSIX") return calendar.weekdaySymbols } enum Weekday: String { case monday, tuesday, wednesday, thursday, friday, saturday, sunday } enum SearchDirection { case next case previous var calendarSearchDirection: Calendar.SearchDirection { switch self { case .next: return .forward case .previous: return .backward } } } } 
+54
source share

You can use the ISO8601 calendar, where the first day of the week is Monday:

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, July 16, 2018 at 12:00:00 AM Brasilia Standard Time" 

as an extension:

 extension Calendar { static let iso8601 = Calendar(identifier: .iso8601) } extension Date { var currentWeekMonday: Date { return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))! } } 

 let currentWeekMonday = Date().currentWeekMonday print(currentWeekMonday.description(with: .current)) // Monday, July 16, 2018 at 12:00:00 AM Brasilia Standard Time 
+27
source share

Here's a simplified version of Sandeep's answer .

Using:

 Date().next(.monday) Date().next(.monday, considerToday: true) Date().next(.monday, direction: .backward) 

Expansion:

 public func next(_ weekday: Weekday, direction: Calendar.SearchDirection = .forward, considerToday: Bool = false) -> Date { let calendar = Calendar(identifier: .gregorian) let components = DateComponents(weekday: weekday.rawValue) if considerToday && calendar.component(.weekday, from: self) == weekday.rawValue { return self } return calendar.nextDate(after: self, matching: components, matchingPolicy: .nextTime, direction: direction)! } public enum Weekday: Int { case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday } 
+9
source share

Here is the extension I created, first it finds Sunday and then 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) } } 
+8
source share

Try using:

 calendar.firstWeekday = 2 

Edit

More specifically: NSCalendar.currentCalendar() returns the user's calendar. According to the docs:

The returned calendar is formed from the settings for the system locales selected by the user, superimposed on any user settings that the user specified in the System settings.

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

 let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! calendar!.firstWeekday = 2 
+3
source share

Addition to answer @Saneep

If you want to get the exact date according to the current / current date (let's say you wanted to convert Monday dateTime β†’ 23-05-2016 12:00:00 23-05-2016 05:35:17 ), try the following:

 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! } 
+1
source share

Quick Solution 4

I found out in accordance with my requirement, where I find out the dates of the next.

 1. Today 2. Tomorrow 3. This Week 4. This Weekend 5. Next Week 6. Next Weekend 

So, I created a Date Extension to get the dates of the current week and next week.

THE 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) } } 

USING:

 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 change the Extension suit your needs.

Thanks!

0
source share

All Articles