月末日期给出了加拿大渥太华时区(夏令时)的不同日期。
我试图在任何时区中获得月底日期。
注意:您可以通过更改时区设置来帮助我(在Mac或iPhone中)在加拿大渥太华。并在操场上粘贴代码
extension Date {
public func setTime(day: Int, month: Int,year:Int, timeZoneAbbrev: String = "UTC") -> Date {
let x: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second]
let cal = Calendar.current
var components = cal.dateComponents(x, from: self)
components.timeZone = TimeZone(abbreviation: timeZoneAbbrev)
components.hour = 0
components.minute = 0
components.second = 0
components.day = day
components.month = month
components.year = year
return cal.date(from: components) ?? self
}
func getMonthGapDate(month: Int) -> Date {
return Calendar.current.date(byAdding: .month, value: month, to: self)!
}
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())!
}
}
let firstDayDate = Date().setTime(day: 1, month: 4, year: 2019)
let startDate = firstDayDate.getMonthGapDate(month: -1)
let endDate = firstDayDate.endOfMonth()
print(firstDayDate)
print(startDate)//Prints 2019-03-01 01:00:00 +0000(Ottawa - Canada time zone) Day light zone
print(endDate)// (This is issue)Prints 2019-03-31 04:00:00 +0000(Ottawa - Canada time zone) Day light zone//It should 2019 - 04 - 30
答案 0 :(得分:1)
使用时区缩写可能会很麻烦,尽管“ UTC”非常安全。
但是,我怀疑您应该使用TimeZone.autoupdatingCurrent
以确保您与当地的午夜有约会。
extension Date {
public func setTime(day: Int, month: Int,year:Int) -> Date {
let x: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second]
let cal = Calendar.current
var components = cal.dateComponents(x, from: self)
components.timeZone = TimeZone.autoupdatingCurrent
components.hour = 0
components.minute = 0
components.second = 0
components.day = day
components.month = month
components.year = year
return cal.date(from: components) ?? self
}
func getMonthGapDate(month: Int) -> Date {
return Calendar.current.date(byAdding: .month, value: month, to: self)!
}
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())!
}
}
这给了我以下输出:
2019-04-01 04:00:00 +0000
2019-03-01 05:00:00 +0000
2019-04-30 04:00:00 +0000
请注意+0000-日期以UTC显示,但代表当地的午夜时间。