我正在尝试从下个月的日期开始计算月(和年)值。我已按照有关如何计算下个月日期的说明进行操作,但我只需要月份值。
我曾短暂地尝试过使用 DateFormatter,但这超出了我对日期的了解。
let calendar = Calendar.current
let rightNow = Date()
let monthOfYear = calendar.component(.month, from: rightNow)
let nextMonthOfYear = calendar.date(byAdding: .month, value: 1, to: rightNow)
如果我们在 6 月,我希望收到下个月的值 7。
最佳答案
您可以从今天的日期中获取年和月的组成部分,将月份值加一,从中创建一个新日期并提取其月份值:
extension Date {
var year: Int {
return Calendar.current.component(.year, from: self)
}
var month: Int {
return Calendar.current.component(.month, from: self)
}
var nextMonth: Date {
return DateComponents(calendar: .current, year: year, month: month+1).date!
}
}
let now = Date() // "28 Jun 2019 17:27"
let nextMonthDate = now.nextMonth // "1 Jul 2019 00:00"
let nextMonth = nextMonthDate.month // 7
或者只是
Date().nextMonth.month // 7
关于Swift 帮助从 future 日期中提取月份值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56812768/