Home > Back-end >  how to get start date and end date of previous month in swift
how to get start date and end date of previous month in swift

Time:10-06

I am new in swift and I am trying to get start date and end date of previous month. I know how to do for current month like this

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

But I don't know how to do for previous month. I tried code but not working

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *currentDate = [NSDate date];

NSDateComponents *components = [calendar components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:currentDate];

components.month = components.month - 1;
components.day = 1;

NSDate *newDate = [calendar dateFromComponents:components];

But it is in objective C Please help!

CodePudding user response:

first you get current month by current date then minus 1 to get previous month

extension Date {

 func addingRmoving(months: Int) -> Date? {
    let calendar = Calendar(identifier: .gregorian)

    var components = DateComponents()
    components.calendar = calendar
    components.timeZone = TimeZone(secondsFromGMT: 0)
    components.month = months

    return calendar.date(byAdding: components, to: self)
 }


var startOfMonth: Date {

    let calendar = Calendar(identifier: .gregorian)
    let components = calendar.dateComponents([.year, .month], from: self)

    return  calendar.date(from: components)!
}


var endOfMonth: Date {
    var components = DateComponents()
    components.month = 1
    components.second = -1
    return Calendar(identifier: .gregorian).date(byAdding: components, to: startOfMonth)!
}



}

and how to use it

let lastMonth = Date().addingRmoving(months: -1)
let fisrtDayOfLastMonth = lastMonth.startOfMonth
let lastDayOfLastMonth = lastMonth.endOfMonth
  • Related