夏令时月末日期问题

Issue with end of month date in DAYLIGHT SAVING TIME

月末日期给出加拿大渥太华时区的不同日期(夏令时)。

我正在尝试获取任何时区的月末日期。

注意:您可以通过更改时区设置(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

使用时区缩写可能会很麻烦,尽管“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 显示,但代表当地午夜。

  • 三月初,渥太华使用夏令时,所以是UTC-5
  • 三月底渥太华使用夏令时,所以是UTC-4