Created
July 29, 2021 15:29
-
-
Save carloe/0c09f8151239f0e9897065f1eab253a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Date { | |
var quarter: Int { | |
let month = Calendar.current.dateComponents([.month], from: self).month! | |
return month / 3 + 1 | |
} | |
var beginningOfQuarter: Date { | |
var calendar = Calendar.current | |
calendar.timeZone = .current | |
let inComps = calendar.dateComponents([.year, .month], from: self) | |
let year = inComps.year! | |
let month = 3 * ((inComps.month! - 1) / 3) + 1 | |
let components = DateComponents(year: year, month: month, day: 1, hour: 0, minute: 0, second: 0) | |
return calendar.date(from: components)! | |
} | |
var endOfQuarter: Date { | |
var calendar = Calendar.current | |
calendar.timeZone = .current | |
let inComps = calendar.dateComponents([.year, .month], from: self) | |
let quarter = self.quarter | |
let year = inComps.year! + 3 * quarter / 12 | |
let month = 3 * quarter % 12 + 1 | |
let components = DateComponents(year: year, month: month, day: 1, hour: 0, minute: 0, second: 0) | |
let date = calendar.date(from: components)! | |
return calendar.date(byAdding: DateComponents(second: -1), to: date)! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment