2017-02-23 17 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 
} 

の日が月曜日の日付を取得するためにGETしようが、それは動作しません...スウィフト3 - 月曜日

+2

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

答えて

4

ここでは、SWIFT 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 = "2017年2月20日12:00 AM"

+0

ありがとう、私は解決策を見つけました! – Anton

+0

これから解決策が見つかったら、答えを受け入れてください。 –

+0

@Antonこれまでの問題も解決できるようになりました。申し訳ありませんが、昨日答えることはできませんでした。 –

関連する問題