在DAYLIGHT SAVING TIME中发布月末日期

问题描述 投票:0回答:1

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

我想在任何时区获得月末日期。

注意:您可以通过更改时区设置(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
ios swift date nsdatecomponents
1个回答
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显示,但代表当地午夜。

  • 3月初,渥太华没有使用夏令时,所以它是UTC-5
  • 3月底,渥太华正在使用夏令时,因此它是UTC-4
© www.soinside.com 2019 - 2024. All rights reserved.