WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Confused about dates

Forums > Swift

I know Paul say Dates are hard (not even the half of it) but wondering if anyone could tell why this happens

I have extension on Date to help with dates

extension Date {
    var startDateOfMonth: Date {
        guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: self)) else {
            fatalError("Unable to get start date from date")
        }
        return date
    }

    var endDateOfMonth: Date {
        guard let date = Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: self.startDateOfMonth) else {
            fatalError("Unable to get end date from date")
        }
        return date
    }

    var dayNumber: Int {
        let components = Calendar.current.dateComponents([.day], from: self)
        guard let day = components.day else {
            fatalError("Unable to get day from date")
        }
        return day
    }
}

Then you use

let startDate = Date.now.startDateOfMonth
print(startDate) // prints 2022-03-01 00:00:00 +0000

let endDate = Date.now.endDateOfMonth
print(endDate) // prints 2022-03-30 23:00:00 +0000

let endDay = endDate.dayNumber
let startDay = startDate.dayNumber
print(startDay, endDay) // print 1 31

Why does endDate print 30th of month however the endDay is 31?

   

Could be an edge case of Daylight saving time this month. We're going to add one hour and then it would match.

   

Printing a Date gets its representation in terms of UTC. (Which is why we're told to always use DateFormatter when presenting dates to users, since that localizes the UTC representation to the user's calendar and time zone.)

DateComponents are localized to a particular calendar and time zone.

So @Hatsushira is on track about the time change, since British Summer Time (UTC+01:00) starts during March. So printing the raw Date shows 30 March while printing a part of DateComponents (which, again, is localized) results in 31.

1      

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.