斯威夫特:阳历和周/工作日 - 行为不一致

时间:2015-05-10 17:34:41

标签: swift calendar

我需要将当前工作日作为Int值,具体取决于用户的区域设置。

但是当使用当前语言环境的格里高利历时,我用以下代码实现了不一致的行为:

// Set calendar
var gregorian = NSCalendar(identifier: NSCalendarIdentifierGregorian)
// Use one of the two following locales:
gregorian?.locale = NSLocale(localeIdentifier: "en_US")
gregorian?.locale = NSLocale(localeIdentifier: "de_DE")

然后我有两个案例:

// CASE 1: Give the calendar week number for today (in this case: May 10, 2015 which is a Sunday) 
// Expected result for US locale: CW 20, for some european locales e.g. DE/Germany: CW 19 due to first day of week = Monday)
var todayDateComps  = gregorian?.components(.CalendarUnitWeekOfYear, fromDate: NSDate())
println(todayDateComps)

所以这里不同的语言环境有效:CW 19用于德语语言环境,CW 20用于美国语言环境。

问题在于第二种情况 - 当前的Int工作日取决于用户的语言环境:

// CASE 2: Give the numeric value for the weekday for today (in this case: May 10, 2015 which is a Sunday)
// Expected results: 1 for US locale, 7 for some european locales e.g. DE/Germany as Monday is first day of week
let comps = gregorian?.components(.CalendarUnitWeekday, fromDate: NSDate())
if let weekday = comps?.weekday {
   println(weekday)
}

区域设置在这里不起作用:案例2在两种情况下都返回" 1"。我做错了什么?

1 个答案:

答案 0 :(得分:0)

weekday不依赖于语言环境。您正在考虑的属性是firstWeekday