better way to get the name of the day on ios swift

sarah picture sarah · Nov 15, 2015 · Viewed 19.2k times · Source

i take the name of the day like this

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"
    }
}

it is working find but it i was wondering if swift comes with some libraries to do that automatically better than me do that in code like manually

Answer

Leo picture Leo · Nov 15, 2015

Use 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"    

Screenshot

enter image description here