如何在Swift系统中获取工作日数组?

时间:2015-02-21 13:59:02

标签: swift xcode6 osx-yosemite

如何从系统中获取星期几的数组(我认为来自NSDate)?

到现在为止,我只能参加当天的比赛,但我希望能够在阵容中占用所有工作日。

如果将星期的第一天设置为星期一,我的数组将如下所示:

[ Mon, Tue, Wed... ]

如果星期的第一天是星期天,我的数组看起来像:

[Sun, Mon, Tue... ]

代码:

let dateNow = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | .CalendarUnitYear , fromDate: dateNow) 

/*This is the way how i take system time */ 

let format = NSDateFormatter()
format.dateFormat = "EEE"
stringDay = format.stringFromDate(dateNow) 

3 个答案:

答案 0 :(得分:26)

尝试these properties

let fmt = NSDateFormatter()
fmt.weekdaySymbols // -> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
fmt.shortWeekdaySymbols // -> ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
fmt.veryShortWeekdaySymbols // -> ["S", "M", "T", "W", "T", "F", "S"]
fmt.standaloneWeekdaySymbols // -> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
fmt.shortStandaloneWeekdaySymbols // -> ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
fmt.veryShortStandaloneWeekdaySymbols // -> ["S", "M", "T", "W", "T", "F", "S"]

看起来他们总是返回Sun ... Sat数组而不管.firstWeekday的{​​{1}}属性。因此,您必须手动旋转

.calendar

答案 1 :(得分:0)

斯威夫特

创建一个DateFrmatter

let formatter: DateFormatter = {
    let formatter = DateFormatter()

    // ? You can setup the formatter here. For example, setting the locale to return the weekdays in the desired language.
    formatter.locale = .init(identifier: "fa")

    return formatter
}()
<块引用>

注意 创建格式化程序是一项非常昂贵的任务,您可能会在主线程中遇到延迟。如果你觉得你会再次需要它,请尝试缓存它

现在您可以使用:

formatter.weekdaySymbols \\ ["یکشنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"]
formatter.veryShortWeekdaySymbols \\ ["ی", "د", "س", "چ", "پ", "ج", "ش"]

注意,您可以使用 en 标识符来获取以上所有英文标识符,例如:

,,,
formatter.locale = .init(identifier: "en")
,,,

formatter.weekdaySymbols // -> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
formatter.shortWeekdaySymbols // -> ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
formatter.veryShortWeekdaySymbols // -> ["S", "M", "T", "W", "T", "F", "S"]

答案 2 :(得分:-1)

如果您希望将星期一作为第一天,则可以使用此扩展程序。

extension SequenceType where Generator.Element == String {
    func mondayFirst(withSunday: (Bool)) -> [String] {
        var tempWeek = self as! [String]

        let tempDay = tempWeek.first

        tempWeek.removeFirst()

        if (!withSunday) {
            tempWeek.append(tempDay!)
        }

        return tempWeek
    }
}