Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

ios - Swift - Weekday by current location by currentCalendar()

Today is Wednesday and I have this code

let calendar:NSCalendar = NSCalendar.currentCalendar()
let dateComps:NSDateComponents = calendar.components(.CalendarUnitWeekday , fromDate: NSDate())
let dayOfWeek:Int = dateComps.weekday

dayOfWeek is 4, but today is 3rd day of the week in Bulgaria. Is in USA today is 4th day of the week? And how to determine when the week starts in different countries and regions ? On my iPhone locale and calendar are set to Bulgarian calendar and locale and it knows that the week starts on Monday on my iMac also, but when I execute code it writes me 4...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For the Gregorian calendar, the weekday property of NSDateComponents is always 1 for Sunday, 2 for Monday etc.

NSCalendar.currentCalendar().firstWeekday

gives the (index of the) first weekday in the current locale, that could be 1 in USA and 2 in Bulgaria. Therefore

var dayOfWeek = dateComps.weekday + 1 - calendar.firstWeekday
if dayOfWeek <= 0 {
    dayOfWeek += 7
}

is the day of the week according to your locale. As a one-liner:

let dayOfWeek = (dateComps.weekday + 7 - calendar.firstWeekday) % 7 + 1

Update for Swift 3:

let calendar = Calendar.current
var dayOfWeek = calendar.component(.weekday, from: Date()) + 1 - calendar.firstWeekday
if dayOfWeek <= 0 {
    dayOfWeek += 7
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...