Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 985
sarah Avatar asked Nov 15 '15 12:11

sarah


3 Answers

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

like image 74
Leo Avatar answered Oct 19 '22 06:10

Leo


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
like image 21
ober Avatar answered Oct 19 '22 07:10

ober


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

like image 1
Ernest Jordan Chechelski Avatar answered Oct 19 '22 06:10

Ernest Jordan Chechelski