get the date for the first day of the current month in swift

You can use the Calendar and Date components to get the first day of the current month in Swift:

main.swift
extension Date {
    var startOfMonth: Date {
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents([.year, .month], from: self)
        return calendar.date(from: components)!
    }
}
236 chars
8 lines

And then you can simply call:

main.swift
let firstDayOfCurrentMonth = Date().startOfMonth
49 chars
2 lines

Or, you can create a function to get the first day of any month for any date:

main.swift
func getFirstDayOfMonth(date: Date) -> Date {
    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents([.year, .month], from: date)
    return calendar.date(from: components)!
}

let currentDate = Date()
let firstDayOfCurrentMonth = getFirstDayOfMonth(date: currentDate)
311 chars
9 lines

gistlibby LogSnag