NSCalendar Additions
Dates. More than any other data type, the gulf between the initial banality of dates and their true, multifaceted complexity looms terrifyingly large. Combining sub-second precision, overlapping units, geopolitical time zone boundaries, localization differences in both language and grammar, and Daylight Saving shifts and leap year adjustments that literally add and remove whole chunks of time from measured existence, there’s a lot to process.
→ nshipster.com/nscalendar-additions/
NSCalendar offers many tools for working with dates beyond basic NSDateComponents.
To get components:
- Use
calendar.component(.hour, from: date)for one part. - Methods like
getEra(_:year:month:day:fromDate:)fetch several at once by reference. - For time:
getHour(_:minute:second:nanosecond:fromDate:). - NSDateComponents has
components(in:from:)for time zone shifts andcomponents(_:from:to:options:)for differences.
For comparisons:
- Check if a date is today, tomorrow, yesterday, or on a weekend with
isDateInToday(_:), etc. - See if two dates share the same day with
isDate(_:inSameDayAs:). - Compare to a unit like week with
isDate(_:equalTo:toUnitGranularity:)orcompareDate(_:toDate:toUnitGranularity:). - Match specific parts with
date(_:matchesComponents:).
For finding next dates:
nextDate(after:matching:options:)and variants find the next match for components, a unit/value, or time of day.- Options handle direction (
.searchBackwards), strictness (.matchStrictly), and missing times like DST (.matchNextTime, etc.).
To list matches: enumerateDates(startingAfter:matching:options:using:).
For weekends: nextWeekendStartDate(_:interval:options:afterDate:) and rangeOfWeekendStartDate(_:interval:containingDate:).
It also gives localised names like monthSymbols, shortMonthSymbols, and standalone versions for grammar rules in some languages.
Category:
Tags:
Year: