DateComponents
Taken in one context, date components can be used to represent a specific calendar date. But in another context, the same object might instead be used as a duration of time. For example, a date components object with year set to 2018, month set to 10, and day set to 10 could represent a period of 2018 years, 10 months, and 10 days or the tenth day of the tenth month in the year 2018.
→ nshipster.com/datecomponents/
The article introduces DateComponents, a versatile Foundation type in Swift for representing either a specific calendar date or a duration of time, emphasising its use over hardcoded time intervals like 60 * 60 * 24 for a day.
As a date specifier, DateComponents can create dates via calendar.date(from:), such as October 10, 2018, or extract components like year, month, and day from a Date using calendar.dateComponents(_:from:).
For durations, it calculates time differences with calendar.dateComponents(_:from:to:), like determining a month’s hours, or adds offsets like “tomorrow” using calendar.date(byAdding:to:). It covers nuanced components like era, quarter, weekdayOrdinal, and yearForWeekOfYear, noting quirks like the Gregorian calendar’s handling of BC/AD and locale-specific week starts.
The article highlights methods like dateInterval(of:for:) for precise range calculations and nextDate(after:matching:matchingPolicy:repeatedTimePolicy:direction:) for complex time-matching scenarios, leveraging Swift’s clear syntax to handle time’s complexity accurately.
Enjoyed this post?
Well, you could share the post with others, follow me via Social Media or RSS Feeds and/or send me a comment via email.
Tags
Category:
Tags:
Year: