### Install DateTools via CocoaPods Source: https://context7.com/matthewyork/datetools/llms.txt Add the 'DateToolsSwift' pod to your Podfile for iOS/macOS projects using CocoaPods. ```ruby # Podfile for Swift projects pod 'DateToolsSwift' ``` ```ruby # Podfile for Objective-C projects (legacy) pod 'DateTools' ``` -------------------------------- ### Install DateTools via Swift Package Manager Source: https://context7.com/matthewyork/datetools/llms.txt Include the DateTools package URL in your Package.swift file for Swift Package Manager integration. ```swift // Package.swift for Swift Package Manager dependencies: [ .package(url: "https://github.com/MatthewYork/DateTools.git", from: "5.0.0") ] ``` -------------------------------- ### Initialize Time Periods in Objective-C Source: https://github.com/matthewyork/datetools/blob/master/README.md Demonstrates creating a DTTimePeriod instance using explicit start/end dates or by specifying a duration and start time. ```objc DTTimePeriod *timePeriod = [[DTTimePeriod alloc] initWithStartDate:startDate endDate:endDate]; ``` ```objc DTTimePeriod *timePeriod = [DTTimePeriod timePeriodWithSize:DTTimePeriodSizeHour amount:5 startingAt:[NSDate date]]; ``` -------------------------------- ### Create and Manage a Time Period Chain Source: https://github.com/matthewyork/datetools/blob/master/README.md Demonstrates initializing a chain, adding time periods, and accessing items by index. Chains automatically adjust start dates to maintain a sequential structure. ```objc //Create chain DTTimePeriodChain *chain = [DTTimePeriodChain chain]; //Create a few time periods DTTimePeriod *firstPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2014 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]]; DTTimePeriod *secondPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2016 11 05 18:15:12.000"]]; //Add test periods [chain addTimePeriod:firstPeriod]; [chain addTimePeriod:secondPeriod]; //Retreive chain items DTTimePeriod *firstPeriod = chain[0]; ``` -------------------------------- ### Lengthen Time Period by Anchor Date Source: https://github.com/matthewyork/datetools/blob/master/README.md Lengthens a time period by anchoring one date and changing the other. This example doubles a 1-minute period to 2 minutes by retaining the end date and shifting the start date. ```objc DTTimePeriod *timePeriod = [DTTimePeriod timePeriodWithSize:DTTimePeriodSizeMinute endingAt:[NSDate date]]; [timePeriod lengthenWithAnchorDate:DTTimePeriodAnchorEnd size:DTTimePeriodSizeMinute amount:1]; ``` -------------------------------- ### Get Time Ago String Source: https://github.com/matthewyork/datetools/blob/master/README.md Generates a human-readable string indicating how long ago a date was relative to the current time. Supports both long and short formats. ```swift let timeAgoDate = 2.days.earlier print("Time Ago: ", timeAgoDate.timeAgoSinceNow) print("Time Ago: ", timeAgoDate.shortTimeAgoSinceNow) ``` -------------------------------- ### Get Relationship Between Two Time Periods Source: https://github.com/matthewyork/datetools/blob/master/README.md Determines the official relationship between two DTTimePeriod objects. The result is an enum value from DTTimePeriodRelation. ```objc -(DTTimePeriodRelation)relationToPeriod:(DTTimePeriod *)period; ``` -------------------------------- ### Create and Manage TimePeriodChain in Swift Source: https://context7.com/matthewyork/datetools/llms.txt Demonstrates creating a TimePeriodChain, adding, inserting, and removing periods. Shows how periods automatically chain together and how the entire chain can be shifted. Useful for managing back-to-back appointments or schedules. ```swift import DateToolsSwift // Create a chain let chain = TimePeriodChain() // Add periods - they automatically chain together let task1 = TimePeriod(beginning: Date(), chunk: 2.hours) let task2 = TimePeriod(beginning: Date(), chunk: 1.hours) // Start date will be adjusted let task3 = TimePeriod(beginning: Date(), chunk: 30.minutes) chain.append(task1) chain.append(task2) // Automatically starts when task1 ends chain.append(task3) // Automatically starts when task2 ends // Access chain properties print("Chain begins: \(chain.beginning!)") print("Chain ends: \(chain.end!)") print("Total tasks: \(chain.count)") print("Total duration: \(chain.duration)") // Access individual periods let firstTask = chain[0] let secondTask = chain[1] print("Task 2 starts: \(secondTask.beginning!)") // Equal to task1.end // Insert a period - shifts all following periods let urgentTask = TimePeriod(beginning: Date(), chunk: 45.minutes) chain.insert(urgentTask, at: 1) // Insert after first task // All subsequent tasks shift later by 45 minutes // Remove a period - preceding periods shift to fill gap chain.remove(at: 1) // Shift entire chain chain.shift(by: 1.hours) // Move all tasks 1 hour later chain.shift(by: -1800) // Move all tasks 30 minutes earlier // Pop last period if let lastTask = chain.pop() { print("Removed last task with duration: \(lastTask.duration)") } // Build a daily schedule let schedule = TimePeriodChain() let dayStart = Date().start(of: .day).add(9.hours) let standup = TimePeriod(beginning: dayStart, chunk: 15.minutes) let coding = TimePeriod(beginning: dayStart, chunk: 3.hours) let lunch = TimePeriod(beginning: dayStart, chunk: 1.hours) let review = TimePeriod(beginning: dayStart, chunk: 2.hours) schedule.append(standup) schedule.append(coding) schedule.append(lunch) schedule.append(review) // Schedule is now: 9:00 standup -> 9:15 coding -> 12:15 lunch -> 13:15 review -> 15:15 print("Day ends at: \(schedule.end!)") ``` -------------------------------- ### Create and Manage a Time Period Collection Source: https://github.com/matthewyork/datetools/blob/master/README.md Demonstrates initializing a collection, adding time periods, and accessing items by index. ```objc //Create collection DTTimePeriodCollection *collection = [DTTimePeriodCollection collection]; //Create a few time periods DTTimePeriod *firstPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2014 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]]; DTTimePeriod *secondPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2016 11 05 18:15:12.000"]]; //Add time periods to the colleciton [collection addTimePeriod:firstPeriod]; [collection addTimePeriod:secondPeriod]; //Retreive collection items DTTimePeriod *firstPeriod = collection[0]; ``` -------------------------------- ### Compare Dates and Calculate Differences Source: https://context7.com/matthewyork/datetools/llms.txt Use boolean comparison methods and time unit helpers to determine relationships between dates or calculate durations. ```swift import DateToolsSwift let date1 = Date() let date2 = date1.add(5.days) let date3 = date1.subtract(2.hours) // Boolean comparisons let isLater = date2.isLater(than: date1) // true let isEarlier = date3.isEarlier(than: date1) // true let isLaterOrEqual = date1.isLaterThanOrEqual(to: date1) // true let isEarlierOrEqual = date3.isEarlierThanOrEqual(to: date1) // true let areEqual = date1.equals(date1) // true let sameDay = date1.isSameDay(date: date2) // false // Calculate time between dates let yearsBetween = date2.years(from: date1) let monthsBetween = date2.months(from: date1) let weeksBetween = date2.weeks(from: date1) let daysBetween = date2.days(from: date1) // 5 let hoursBetween = date2.hours(from: date1) // 120 let minutesBetween = date2.minutes(from: date1) let secondsBetween = date2.seconds(from: date1) // Time until a future date let futureDate = Date().add(10.days) print(futureDate.daysUntil) // 10 print(futureDate.hoursUntil) // 240 print(futureDate.minutesUntil) // 14400 // Time since a past date let pastDate = Date().subtract(3.weeks) print(pastDate.weeksAgo) // 3 print(pastDate.daysAgo) // 21 print(pastDate.hoursAgo) // 504 // Get the chunk of time between two dates let birthday = Date(year: 2000, month: 6, day: 15, hour: 0, minute: 0, second: 0) let age = birthday.chunkBetween(date: Date()) print("Years: \(age.years), Months: \(age.months), Days: \(age.days)") // Earlier/later date helpers let earlier = date1.earlierDate(date2) // Returns date1 let later = date1.laterDate(date2) // Returns date2 ``` -------------------------------- ### Access Date Components Source: https://github.com/matthewyork/datetools/blob/master/README.md Simplifies accessing individual date components like year and month directly from a Date object, reducing boilerplate code. ```swift let year = Date().year let month = Date().month ``` -------------------------------- ### Create Calendar-Aware Time Intervals (TimeChunks) Source: https://context7.com/matthewyork/datetools/llms.txt Use expressive integer extensions provided by DateToolsSwift to create TimeChunks, representing calendar-aware time units. These account for daylight savings, leap years, and varying month lengths. TimeChunks can be combined and used to calculate future or past dates. ```swift import DateToolsSwift // Create TimeChunks using integer extensions let twoHours = 2.hours let threeDays = 3.days let oneWeek = 1.weeks let sixMonths = 6.months let oneYear = 1.years // Combine TimeChunks let combinedChunk = 1.years + 2.months + 3.days let anotherChunk = TimeChunk(seconds: 30, minutes: 15, hours: 2, days: 5, weeks: 0, months: 1, years: 0) // Get dates relative to now let tomorrow = 1.days.later // Date: tomorrow let yesterday = 1.days.earlier // Date: yesterday let nextMonth = 1.months.later // Date: one month from now let lastYear = 1.years.earlier // Date: one year ago // Get dates relative to a specific date let specificDate = Date() let futureDate = 2.weeks.later(than: specificDate) let pastDate = 3.months.earlier(than: specificDate) // Convert TimeChunks to different units (approximate) let daysInWeeks = 14.days.to(.weeks) // 2 let hoursInDays = 48.hours.to(.days) // 2 let secondsInHours = 2.hours.to(.seconds) // 7200 ``` -------------------------------- ### Analyze TimePeriod Relationships Source: https://context7.com/matthewyork/datetools/llms.txt Use these methods to compare two time periods, check for overlaps, detect gaps, and verify if a date falls within a specific period. ```swift import DateToolsSwift let period1 = TimePeriod(beginning: Date(), chunk: 2.weeks) let period2 = TimePeriod(beginning: Date().add(1.weeks), chunk: 2.weeks) let period3 = TimePeriod(beginning: Date().add(1.months), chunk: 1.weeks) // Check relationships let relation = period1.relation(to: period2) // Returns Relation enum // Possible values: .after, .before, .startTouching, .endTouching, // .startInside, .endInside, .inside, .enclosing, .exactMatch, etc. // Boolean relationship checks let areEqual = period1.equals(period2) // false let isInside = period2.isInside(of: period1) // false let contains = period1.contains(period2) // false let overlaps = period1.overlaps(with: period2) // true (they share time) let intersects = period1.intersects(with: period2) // true (overlap or touch) // Check if period contains a date let testDate = Date().add(3.days) let containsDate = period1.contains(testDate, interval: .closed) // true // Gap detection let hasGap = period1.hasGap(between: period3) // true let gapDuration: TimeInterval = period1.gap(between: period3) // Gap in seconds let gapChunk: TimeChunk? = period1.gap(between: period3) // Gap as TimeChunk // Before/After checks let isBefore = period1.isBefore(period: period3) // true let isAfter = period3.isAfter(period: period1) // true // Example: Check if current time is within business hours let now = Date() let businessHours = TimePeriod( beginning: now.start(of: .day).add(9.hours), end: now.start(of: .day).add(17.hours) ) let isOpen = businessHours.contains(now, interval: .closed) print("Business is open: \(isOpen)") ``` -------------------------------- ### Generate Relative Time Strings with DateTools Source: https://context7.com/matthewyork/datetools/llms.txt Use DateToolsSwift to generate human-readable relative time strings from dates. Supports various formats and languages. Ensure the DateToolsSwift import. ```swift import DateToolsSwift // Get relative time strings from a date let pastDate = Date().subtract(2.days) print(pastDate.timeAgoSinceNow) // Output: "2 days ago" print(pastDate.shortTimeAgoSinceNow) // Output: "2d" // More examples let hourAgo = Date().subtract(1.hours) print(hourAgo.timeAgoSinceNow) // Output: "An hour ago" let weekAgo = Date().subtract(1.weeks) print(weekAgo.timeAgoSinceNow) // Output: "Last week" // Static method usage let oldDate = Date().subtract(3.months) print(Date.timeAgo(since: oldDate)) // Output: "3 months ago" // Short format (Twitter-style) let minutesAgo = Date().subtract(45.minutes) print(minutesAgo.shortTimeAgoSinceNow) // Output: "45m" ``` -------------------------------- ### Manage TimePeriodCollection Source: https://context7.com/matthewyork/datetools/llms.txt Use TimePeriodCollection to group multiple time periods, perform bulk operations, and query for intersections or containment. ```swift import DateToolsSwift // Create a collection let collection = TimePeriodCollection() // Add time periods let meeting1 = TimePeriod(beginning: Date(), chunk: 1.hours) let meeting2 = TimePeriod(beginning: Date().add(2.hours), chunk: 1.hours) let meeting3 = TimePeriod(beginning: Date().add(30.minutes), chunk: 45.minutes) collection.append(meeting1) collection.append(meeting2) collection.append(meeting3) // Add multiple periods at once let morePeriods = [ TimePeriod(beginning: Date().add(4.hours), chunk: 30.minutes), TimePeriod(beginning: Date().add(5.hours), chunk: 1.hours) ] collection.append(morePeriods) // Access collection properties print("Collection beginning: \(collection.beginning!)") print("Collection end: \(collection.end!)") print("Total periods: \(collection.count)") print("Collection duration: \(collection.duration)") // Access individual periods let firstPeriod = collection[0] // Sorting collection.sortByBeginning() // Get sorted copy without modifying original let sortedCollection = collection.sortedByBeginning() // Custom sorting let sortedByDuration = collection.sorted { $0.duration < $1.duration } // Find periods that intersect with a date let checkDate = Date().add(35.minutes) let intersectingPeriods = collection.periodsIntersected(by: checkDate) print("Periods at time: \(intersectingPeriods.count)") // Find periods that intersect with another period let searchPeriod = TimePeriod(beginning: Date(), chunk: 1.hours) let overlapping = collection.periodsIntersected(by: searchPeriod) // Find all periods inside a given period let dayPeriod = TimePeriod(beginning: Date().start(of: .day), chunk: 1.days) let todaysMeetings = collection.allInside(in: dayPeriod) // Remove periods collection.remove(at: 0) collection.removeAll() // Map over collection let extendedCollection = collection.map { period -> TimePeriodProtocol in return TimePeriod(beginning: period.beginning, chunk: period.chunk + 15.minutes) } ``` -------------------------------- ### Manipulate Dates with DateToolsSwift Source: https://context7.com/matthewyork/datetools/llms.txt Perform date arithmetic using TimeChunks, operator overloads, and component-based start/end calculations. ```swift import DateToolsSwift let now = Date() // Add time using TimeChunk let inTwoWeeks = now.add(2.weeks) let nextYear = now.add(1.years) let inThreeHours = now.add(3.hours) // Subtract time using TimeChunk let twoWeeksAgo = now.subtract(2.weeks) let lastMonth = now.subtract(1.months) // Use operator overloads let tomorrow = now + 1.days let yesterday = now - 1.days let futureDate = now + 2.years + 3.months + 5.days // Get start and end of date components let startOfDay = now.start(of: .day) // Midnight of current day let endOfDay = now.end(of: .day) // 23:59:59.999 of current day let startOfMonth = now.start(of: .month) // First day of month at midnight let endOfMonth = now.end(of: .month) // Last day of month at 23:59:59.999 let startOfYear = now.start(of: .year) // January 1st at midnight let endOfYear = now.end(of: .year) // December 31st at 23:59:59.999 // Chain operations let complexDate = now .add(1.months) .subtract(3.days) .start(of: .day) ``` -------------------------------- ### Add Years to Date Source: https://github.com/matthewyork/datetools/blob/master/README.md Easily create a new date by adding a specified number of years to an existing date. This is a more concise alternative to manual calendar operations. ```objc NSDate *newDate = [date dateByAddingYears:1]; ``` -------------------------------- ### Manage Time Periods Source: https://context7.com/matthewyork/datetools/llms.txt Represent time spans using the TimePeriod class, supporting initialization, duration manipulation, and shifting. ```swift import DateToolsSwift // Initialize with start and end dates let startDate = Date() let endDate = startDate.add(2.weeks) let vacation = TimePeriod(beginning: startDate, end: endDate) // Initialize with duration let meeting = TimePeriod(beginning: Date(), duration: 3600) // 1 hour meeting let event = TimePeriod(end: Date(), duration: 7200) // 2-hour event ending now // Initialize with TimeChunk let project = TimePeriod(beginning: Date(), chunk: 3.months) let deadline = TimePeriod(end: Date().add(1.years), chunk: 2.weeks) // Get duration information print(vacation.days) // 14 print(vacation.hours) // 336 print(vacation.minutes) // 20160 print(vacation.duration) // TimeInterval in seconds print(vacation.isMoment) // false (start != end) // Get duration as TimeChunk let chunk = vacation.chunk print("Duration: \(chunk.weeks) weeks, \(chunk.days) days") // Shift period (move both start and end) var shiftedPeriod = vacation.shifted(by: 1.weeks) // Shift by TimeChunk shiftedPeriod = vacation.shifted(by: 86400) // Shift by TimeInterval // In-place shift var mutablePeriod = TimePeriod(beginning: Date(), end: Date().add(1.days)) mutablePeriod.shift(by: 2.days) // Lengthen/shorten period let longerPeriod = vacation.lengthened(by: 3.days, at: .end) // Extend end let shorterPeriod = vacation.shortened(by: 1.weeks, at: .beginning) // Shrink from start let centeredLonger = vacation.lengthened(by: 86400, at: .center) // Expand from center // Operator overloads let extended = vacation + 1.weeks // Lengthen by 1 week let shortened = vacation - 3.days // Shorten by 3 days ``` -------------------------------- ### Calculate Years Between Dates in Objective-C Source: https://github.com/matthewyork/datetools/blob/master/README.md Compares the difference between two dates using standard NSCalendar logic versus the simplified DateTools method. ```objc NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:[NSDate defaultCalendar]]; NSDate *earliest = [firstDate earlierDate:secondDate]; NSDate *latest = (secondDate == firstDate) ? secondDate : firstDate; NSInteger multiplier = (secondDate == firstDate) ? -1 : 1; NSDateComponents *components = [calendar components:allCalendarUnitFlags fromDate:earliest toDate:latest options:0]; NSInteger yearsApart = multiplier*(components.month + 12*components.year); ``` ```objc NSInteger yearsApart = [firstDate yearsFrom:secondDate]; ``` -------------------------------- ### Access Date Components Directly in Swift Source: https://context7.com/matthewyork/datetools/llms.txt Access individual date components (year, month, day, hour, etc.) and perform boolean checks (isToday, isWeekend) directly from a Date object using DateToolsSwift extensions. Modification of components is also supported. ```swift import DateToolsSwift let date = Date() // Access individual components let year = date.year // e.g., 2024 let month = date.month // 1-12 let day = date.day // 1-31 let hour = date.hour // 0-23 let minute = date.minute // 0-59 let second = date.second // 0-59 // Access additional calendar components let weekday = date.weekday // 1-7 (Sunday = 1) let weekdayOrdinal = date.weekdayOrdinal let quarter = date.quarter let weekOfMonth = date.weekOfMonth let weekOfYear = date.weekOfYear let daysInMonth = date.daysInMonth // 28-31 depending on month // Boolean checks let isLeapYear = date.isInLeapYear let isToday = date.isToday let isTomorrow = date.isTomorrow let isYesterday = date.isYesterday let isWeekend = date.isWeekend // Modify components var mutableDate = date mutableDate.year(2025) mutableDate.month(6) mutableDate.day(15) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.