Snooze Snooze - 1 year ago 95
Swift Question

Get the first day of a month in swift

I'm looking for a way to get the first day of a month (in Swift).
I would like to know if it is a Monday, Tuesday etc... by returning the number corresponding.

I try many solution like getting a NSCalendar component .weekDay but no one work.

Example :


// Should return : 0 (because the first day of February 2016 is Monday).

Any help would be appreciate.

Answer Source

Well to get the corresponding number of the day of the week you can use:

var weekday = calendar!.component(NSCalendarUnit.Weekday, fromDate: yourNSDate)
var weekdayName = self.getDayOfWeek(weekday)

Then you can call this function I created to get the corresponding name of the day of the week based on the number passed in to getDayOfWeek()

func getDayOfWeek(weekday:Int) -> String {
        if(weekday == 1) {
            return "Sunday"
        else if(weekday == 2) {
            return "Monday"
        else if(weekday == 3) {
            return "Tuesday"
        else if(weekday == 4) {
            return "Wednesday"
        else if(weekday == 5) {
            return "Thursday"
        else if(weekday == 6) {
            return "Friday"
        else {
            return "Saturday"


And if you are using a String as a date to begin with you can change it into an NSDate like this:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /*place date format here*/
let date = dateFormatter.dateFromString(/*your_date_string*/)