I compute 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 fine but I was wondering if Swift comes with some libraries to do that automatically.
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
If you want to get the array of day names you could use: weekdaySymbols in Calendar()
example:
let calendar = Calendar(identifier: .gregorian)
let days = calendar.weekdaySymbols
You can check also this 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
- stands for day of the week, good answer, official source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With