Como obter a data de segunda-feira da semana atual em tempo

Estou tentando obter a data de segunda-feira da semana atual. Isso é tratado como o primeiro dia da semana na minha exibição de tabela. Eu também preciso pegar o domingo da semana atual. Isso é tratado como o último dia da semana na minha exibição de tabela.

Tentativa atual:

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 

Eu escrevi extensões de data para obter a data para determinado dia da semana e aqui está como é fácil usá-la com o Swift 4,

 Date.today().next(.monday) // Feb 12, 2018 at 12:00 AM Date.today().next(.sunday) // Feb 11, 2018 at 12:00 AM Date.today().previous(.sunday) // Feb 4, 2018 at 12:00 AM Date.today().previous(.monday) // Feb 5, 2018 at 12:00 AM Date.today().previous(.thursday) // Feb 1, 2018 at 12:00 AM Date.today().next(.thursday) // Feb 15, 2018 at 12:00 AM Date.today().previous(.thursday, considerToday: true) // Feb 8, 2018 at 11:04 PM Date.today().next(.monday) .next(.sunday) .next(.thursday) // Feb 22, 2018 at 12:00 AM 

E aqui está a extensão Data para isso,

 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.index(of: dayName)! + 1 let calendar = Calendar(identifier: .gregorian) if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex { return self } var nextDateComponent = DateComponents() 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 } } } } 

Você pode usar o calendar ISO8601, onde o primeiro dia da semana é segunda-feira:

Swift 3 ou posterior

 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" 

como uma extensão:

 extension Date { var cureentWeekMonday: Date { return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))! } } 

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

Aqui está a extensão que criei, primeiro ele encontra domingo e depois adiciona um dia

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

Tente usar:

 calendar.firstWeekday = 2 

Editar

Para ser mais específico: NSCalendar.currentCalendar() retorna o calendar do usuário. Segundo docs:

O calendar retornado é formado pelas configurações da localidade do sistema escolhida pelo usuário atual, sobrepostas a quaisquer configurações personalizadas especificadas pelo usuário em Preferências do Sistema.

Se você quiser sempre segunda-feira como primeiro dia, eu acho que você deveria usar:

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

Aqui está uma versão simplificada da resposta de Sandeep .

Uso:

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

Extensão:

 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 } 

Além da resposta do @Saneep

Se você gostaria de obter o dateTime exato de acordo com a data atual / dada (digamos que você quisesse converter o dateTime de segunda-feira -> 23-05-2016 12:00:00 para 23-05-2016 05:35:17 ) tente este :

 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! }