Home > Software design >  Swift get days since in PST issue
Swift get days since in PST issue

Time:08-07

I'm trying to get the days since in PST but I'm receiving the following 0001-01-01 07:52:58 0000 when calling the method. The method is an extension on Date and the incoming date is the same format 2022-08-07 08:32:57 0000. Not sure where the error is.

func daysInPST() -> Int {
        var components = DateComponents()
        components.timeZone = TimeZone(abbreviation: "PST")
        let currentDateInPST = Calendar.current.date(from: components)
        let days = Calendar.current.dateComponents([.day], from: self, to: currentDateInPST!)
        return days.day!
    }

CodePudding user response:

Calendar.current.date(from: DateComponents()) returns Januar 1st in year 1 because all properties are empty (nil).

If you want to get the days from self to the current date in PST create a custom calendar and set its time zone accordingly

extension Date {
    func daysInPST() -> Int {
        var calendar = Calendar(identifier: .gregorian)
        calendar.timeZone = TimeZone(abbreviation: "PST")!
        return calendar.dateComponents([.day], from: self, to: .now).day!
    }
}
  • Related