Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift get days since in PST issue

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!
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading