Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Weekday from Date - Swift 3

Tags:

date

xcode

swift3

I have looked around a bit, but didnt find a quick answer for this in swift 3. I get todays weekday like this:

let weekday = Calendar.current.component(.weekday, from: Date())

But instead, i would like to get the weekday of a given date. How is this done? Thanx

like image 841
Martin Vidic Avatar asked Dec 09 '16 21:12

Martin Vidic


3 Answers

Presumably you have a Date already?

let weekday = Calendar.current.component(.weekday, from: myDate)

Maybe you want the name of the weekday?

let f = DateFormatter()

f.weekdaySymbols[Calendar.current.component(.weekday, from: Date()) - 1]

The -1 is added at the end because Calendar.current.component(.weekday, from: Date()) returns values from 1-7 but weekdaySymbols expects array indices.

Investigate the NSCalendar/DateComponents api or edit your question to be more specific if you need help with the DateComponents api.

like image 98
Joe Daniels Avatar answered Nov 24 '22 13:11

Joe Daniels


let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy" // OR "dd-MM-yyyy"

let currentDateString: String = dateFormatter.string(from: date)
print("Current date is \(currentDateString)")
   

Current date is Monday, June 29, 2017

like image 28
Yakup Ad Avatar answered Nov 24 '22 15:11

Yakup Ad


Swift5 get week day from DateFormatter

 func getTodayWeekDay()-> String{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "EEEE"
        let weekDay = dateFormatter.string(from: Date())
        return weekDay
  }

 //eg: // "EEEE" --> "Friday" 
       // "EEE"  --> "Fri"
like image 28
Sukh Avatar answered Nov 24 '22 14:11

Sukh