LAST CHANCE: Save 50% on all my Swift books and bundles! >>

SOLVED: Calculating first and last day of the month.

Forums > Swift

Apologies for the questions but I have another. I just don't get dates in Swift.

If anyone can give me guidance here it would really help.

I need to calculate the first and last date of the "current month", and the first and last date of the "previous 11 months". So assuming March 1st is today I need to get something like this:

03012023 03012023
02012023 02282023
01012023 01312023
...
...
...
02012022 02282022

Anything you folks can advise on would be super.

Thank you!

3      

You can get first and last days of the month like so:

extension Date {
    var startDateOfMonth: Date {
        guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: self)) else {
            fatalError("Unable to get start date from date")
        }
        return date
    }

    var endDateOfMonth: Date {
        guard let date = Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: self.startDateOfMonth) else {
            fatalError("Unable to get end date from date")
        }
        return date
    }
}

and then format those dates as needed.

3      

Here is more eleborated example. Just add guard statements as needed

extension Date {

    func getLast6Month() -> Date? {
        return Calendar.current.date(byAdding: .month, value: -6, to: self)
    }

    func getLast3Month() -> Date? {
        return Calendar.current.date(byAdding: .month, value: -3, to: self)
    }

    func getYesterday() -> Date? {
        return Calendar.current.date(byAdding: .day, value: -1, to: self)
    }

    func getLast7Day() -> Date? {
        return Calendar.current.date(byAdding: .day, value: -7, to: self)
    }
    func getLast30Day() -> Date? {
        return Calendar.current.date(byAdding: .day, value: -30, to: self)
    }

    func getPreviousMonth() -> Date? {
        return Calendar.current.date(byAdding: .month, value: -1, to: self)
    }

    // This Month Start
    func getThisMonthStart() -> Date? {
        let components = Calendar.current.dateComponents([.year, .month], from: self)
        return Calendar.current.date(from: components)!
    }

    func getThisMonthEnd() -> Date? {
        let components:NSDateComponents = Calendar.current.dateComponents([.year, .month], from: self) as NSDateComponents
        components.month += 1
        components.day = 1
        components.day -= 1
        return Calendar.current.date(from: components as DateComponents)!
    }

    //Last Month Start
    func getLastMonthStart() -> Date? {
        let components:NSDateComponents = Calendar.current.dateComponents([.year, .month], from: self) as NSDateComponents
        components.month -= 1
        return Calendar.current.date(from: components as DateComponents)!
    }

    //Last Month End
    func getLastMonthEnd() -> Date? {
        let components:NSDateComponents = Calendar.current.dateComponents([.year, .month], from: self) as NSDateComponents
        components.day = 1
        components.day -= 1
        return Calendar.current.date(from: components as DateComponents)!
    }

    //3 Months End
    func getLast3MonthsEnd() -> Date? {
        let components:NSDateComponents = Calendar.current.dateComponents([.year, .month], from: self) as NSDateComponents
        components.month -= 2
        components.day = 1
        components.day -= 1
        return Calendar.current.date(from: components as DateComponents)!
    }

    //6 Months Start
    func getLast6MonthsStart() -> Date? {
        let components:NSDateComponents = Calendar.current.dateComponents([.year, .month], from: self) as NSDateComponents
        components.month -= 6
        return Calendar.current.date(from: components as DateComponents)!
    }

    //6 Months End
    func getLast6MonthsEnd() -> Date? {
        let components:NSDateComponents = Calendar.current.dateComponents([.year, .month], from: self) as NSDateComponents
        components.month -= 5
        components.day = 1
        components.day -= 1
        return Calendar.current.date(from: components as DateComponents)!
    }

}

let startDate6 = Date().getLast6MonthsEnd()!
let endDate6 = Date().getLast6Month()!

let startDate3 = Date().getLast3MonthsEnd()!
let endDate3 = Date().getLast3Month()!

5      

Thank you folks, this is an amazing start I can build from.

3      

There is a simple way to get the start and end of the current month.

Calendar.current.dateInterval(of: .month, for: Date())

Since the interval assumes up to but not including the end date, the end date will be the start of the next month.

Similarly, you can obtain the interval for the week with .weekOfYear as follows.

Calendar.current.dateInterval(of: .weekOfYear, for: Date())

The week interval observes the locale's start of week setting.

3      

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.