更好的方式来获得ios swift上的一天的名字

时间:2015-11-15 12:23:40

标签: ios swift cocoa swift2

我取这样的一天的名字

func loadDayName(forDate date: NSDate) -> String{
    let myComponents = calendar.components(.Weekday, fromDate: date)
    let weekDay = myComponents.weekday
    switch weekDay {
    case 1:
        return "Sunday"
    case 2:
        return "Monday"
    case 3:
        return "Tuesday"
    case 4:
        return "Wednesday"
    case 5:
        return "Thursday"
    case 6:
        return "Friday"
    case 7:
        return "Saturday"
    default:
        return "Nada"
    }
}

它正在寻找但是我想知道swift是否自带了一些库自动比我在手动代码中做得更好

3 个答案:

答案 0 :(得分:49)

使用DateFormatter

Swift 4

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
let dayInWeek = dateFormatter.string(from: date)

Swift3

let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat  = "EEEE" // "EE" to get short style
let dayInWeek = dateFormatter.stringFromDate(date) // "Sunday"    

截图

enter image description here

答案 1 :(得分:4)

如果要获取日期名称数组,可以使用:weekdaySymbols in Calendar()

示例:

let calendar = Calendar(identifier: .gregorian)
let days = calendar.weekdaySymbols

答案 2 :(得分:1)

你也可以检查这个 DateFormatter

let dayNameFormatter: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = .current
    dateFormatter.calendar = .current
    dateFormatter.dateFormat = "cccc"
    return dateFormatter
}()
print(dayNameFormatter.string(from: Date())) Prints today's day name ?

c - 代表星期几,good answerofficial source