每当我使用此方法时,它总是显示错误的日期。
func startOfMonth() -> Date {
let calendar = Calendar.current
let currentDateComponents = calendar.dateComponents([.year, .day, .month], from: self)
return calendar.date(from: currentDateComponents) ?? Date()
}
输出:
2018-10-31 18:30:00 +0000
我想要:
2018-11-1 18:30:00 +0000
答案 0 :(得分:1)
如果您愿意获取每月的第一天,则不应获取原始日期的日期部分:
extension Date {
var startOfMonth: Date {
return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: self))!
}
}
Date().startOfMonth.description(with: .current) // "Thursday, November 1, 2018 at 12:00:00 AM Brasilia Standard Time"