2017-02-23 77 views
0
func GetMondayfromDate(_ date: Date) -> Date { 
    var mdate: Date 
    let calendar = Calendar(identifier: .iso8601) 
    var components = calendar.dateComponents(in: TimeZone(identifier: "UTC")!, from: date) 
    components.weekday = 1 //today is Thursday, but weekday == 5 ?? 
    mdate = calendar.date(from: components)! 
    return mdate 
} 

Попытка получить дату понедельника, но это не работает ...Swift 3 - Получить дату понедельника

+2

http://stackoverflow.com/questions/33397101/how-to-get-mondays-date-of-the-current-week-in-swift –

ответ

4

здесь является Свифт 3 Раствора

кредит: this

import Foundation 

func getWeekDaysInEnglish() -> [String] { 
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! 
calendar.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale 
return calendar.weekdaySymbols 
} 

enum SearchDirection { 
case Next 
case Previous 

    var calendarOptions: NSCalendar.Options { 
    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.index(of: dayName)! + 1 // weekday is in form 1 ... 7 where as index is 0 ... 6 

let today = NSDate() 

let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! 

if consider && calendar.component(.weekday, from: today as Date) == nextWeekDayIndex { 
    return today 
} 

let nextDateComponent = NSDateComponents() 
nextDateComponent.weekday = nextWeekDayIndex 


let date = calendar.nextDate(after: today as Date, matching: nextDateComponent as DateComponents, options: direction.calendarOptions) 
return date! as NSDate 
} 
get(direction: .Previous, "Monday", considerToday: true) 

OUTPUT = "20 февраля 2017, 12:00 AM"

+0

Спасибо, я нашел решение! – Anton

+0

Затем, пожалуйста, примите ответ, если найдете решение. –

+0

@ Антон теперь вы можете решить свою предыдущую проблему также .. Извините, не мог ответить на это вчера. –