[英]How to get start date and end date of previous month in Swift
我是 Swift 的新人,我正在嘗試獲取上個月的開始日期和結束日期。 我知道這個月該怎么做
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())!
}
}
但是我不知道上個月該怎么做。 我試過代碼但沒有工作
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];
但它在目標 C 中。
首先你得到當前日期的當前月份,然后減去 1 得到上個月
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)!
}
}
以及如何使用它
let lastMonth = Date().addingRmoving(months: -1)
let fisrtDayOfLastMonth = lastMonth.startOfMonth
let lastDayOfLastMonth = lastMonth.endOfMonth
//Mark: - To get last months first day's date
func getLastMonthsFirstDay() -> Date {
let calendar = Calendar.current
let currentDate = Date()
var components = calendar.dateComponents([.day, .month, .day], from: currentDate)
components.month = components.month! - 1
components.day = 1
return calendar.date(from: components)!
}
//Mark: - To get last months last day's date
func getLastMonthsLastDay() -> Date {
let calendar = Calendar.current
let currentDate = Date()
var components = calendar.dateComponents([.day, .month, .day], from: currentDate)
components.month = components.month! - 1
components.day = -1
return calendar.date(from: components)!
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.