UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

2      

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

2      

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.

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.