Search code examples
iosdateswift3nsdatensdateformatter

How to get start date and end date of the current month (Swift 3)


I'm trying to get the start and end dates of the current month in dd/MM/yyyy format. I tried using extension as answered in this SO Question.But it seems like it's not what I want(the format is different and also it's giving me last month's last date and current month last but one date ). Can some one help me.

Extension Class:

extension Date {
    func startOfMonth() -> Date? {
        let comp: DateComponents = Calendar.current.dateComponents([.year, .month, .hour], from: Calendar.current.startOfDay(for: self))
        return Calendar.current.date(from: comp)!
    }

    func endOfMonth() -> Date? {
        var comp: DateComponents = Calendar.current.dateComponents([.month, .day, .hour], from: Calendar.current.startOfDay(for: self))
        comp.month = 1
        comp.day = -1
        return Calendar.current.date(byAdding: comp, to: self.startOfMonth()!)
    }
}

My Struct:

struct Constants{

    // keys required for making a Login call (POST Method)
    struct LoginKeys {
       .....
    }

    struct RankingKeys {

        static let DateFrom = String(describing: Date().startOfMonth()) //giving me 2016-11-30 16:00:00 +0000 
        static let DateTo  = String(describing: Date().endOfMonth())
//2016-12-30 16:00:00 +0000
    }
}

Expected Result:

DateFrom  = "01/12/2016"
DateTo = "31/12/2016"

Solution

  • You should write this simple code:

    let dateFormatter = DateFormatter()
    let date = Date()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    

    For start Date:

    let comp: DateComponents = Calendar.current.dateComponents([.year, .month], from: date)
    let startOfMonth = Calendar.current.date(from: comp)!
    print(dateFormatter.string(from: startOfMonth))
    

    For end Date:

    var comps2 = DateComponents()
    comps2.month = 1
    comps2.day = -1
    let endOfMonth = Calendar.current.date(byAdding: comps2, to: startOfMonth)
    print(dateFormatter.string(from: endOfMonth!))