Removing components from a Date in Swift

Sponsored
RevenueCat logo
Codemagic CI/CD for mobile teams

What do you get when you put love for iOS and DevOps together? Answer: Codemagic CI/CD

We recently fixed a bug in our app Helm which occurred when trying to set the time of a scheduled release using the App Store Connect API.

The date we were sending in the request contained the day, month, year, hour and minute, but the API would only allow us to be precise up to the hour.

To fix the issue as quickly as possible and as SwiftUI’s DatePicker can not be configured to only allow the user to select the hour of the day without specifying the minute, we decided to remove the extra information from the date before sending it to the API with a small extension on Date:

Date+KeepingInformation.swift
extension Date {
    func keepingInformation(
        dateComponents: Set<Calendar.Component> = [.year, .month, .day, .hour],
        in calendar: Calendar = .current
    ) -> Date {
        let dateComponents = calendar.dateComponents(dateComponents, from: self)
        
        return calendar.date(from: dateComponents) ?? self
    }
}

The code above extracts the desired date components from the Date instance and then uses the provided Calendar to create a new Date just with those components.