DEV Community

Caleb Hearth
Caleb Hearth

Posted on • Originally published at calebhearth.com on

Truncate Date to Calendar.Component in Swift

I’m frequently wanting to work with truncated dates in Swift apps, especially when dealing with Swift Charts. Foundation provides Calendar.startOfDay(for:) to get the first moment of a day, and that’s been really useful. The extension below will do something similar for an arbitrary1 Calendar.Component to truncate that date to the first moment of that component.

extension Date { /// Returns the first moment of a given Calendar.Component, as a Date. /// /// For example, pass in `.hour` called on `Date()`, if you want the start of /// the current hour of the current day. /// Supported Calendar.Components are .year, .month, .day, .hour, .minute, /// .second. Passing an unsupported component will cause `self` to be returned /// unchanged. /// Calling `.start(of: .day)` is equivalent to calling `.startOfDay`. /// - parameter to: The smallest component you want /// - returns: The first moment of the given date. func start(of component: Calendar.Component) -> Date { let allComponents =...
Enter fullscreen mode Exit fullscreen mode

Read More

Top comments (0)