Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first day of a month in swift

Tags:

swift

calendar

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 :

print(getTheFirstDate("2016-2-18"))

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

Any help would be appreciate.

like image 607
Snooze Avatar asked Dec 08 '22 22:12

Snooze


1 Answers

First you need to parse your date string, then you can use Calendar method dateComponents to get the calendar, year and month components from that date and create a new date from those components. Then you can extract the weekday date component from it:

Xcode 11.5 • Swift 5.2

extension Date {
    var weekday: Int { Calendar.current.component(.weekday, from: self) }
    var firstDayOfTheMonth: Date {
        Calendar.current.dateComponents([.calendar, .year,.month], from: self).date!
    }
}

extension String {
    static var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter
    }()
    
    var date: Date? {
       String.dateFormatter.date(from: self)
    }
}

"2016-2-18".date?.firstDayOfTheMonth.weekday   // 2 = Monday (Sunday-Saturday 1-7)
like image 187
Leo Dabus Avatar answered May 29 '23 07:05

Leo Dabus