### Install SwiftDate with Carthage Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/0.Informations.md Guide to using SwiftDate with Carthage, a decentralized dependency manager. Install Carthage via Homebrew, then add the SwiftDate repository to your Cartfile. Run 'carthage update' and link the framework. ```bash $ brew update $ brew install carthage ``` ```ogdl github "malcommac/SwiftDate" ~> 6.0 ``` -------------------------------- ### Install SwiftDate with CocoaPods Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/0.Informations.md Instructions for integrating SwiftDate into an Xcode project using CocoaPods. Requires CocoaPods 1.1+ and specifies the SwiftDate version. After adding to the Podfile, run 'pod install'. ```bash $ gem install cocoapods ``` ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '10.0' use_frameworks! target '' do pod 'SwiftDate', '~> 5.0' end ``` ```bash $ pod install ``` -------------------------------- ### SwiftDate: Derived Dates Generation Examples Source: https://context7.com/malcommac/swiftdate/llms.txt Illustrates SwiftDate's capabilities for generating derived dates from existing ones. This includes finding the start and end of various time periods (day, week, month), calculating tomorrow/yesterday variations, and navigating to next/previous periods. ```swift import SwiftDate let date = DateInRegion(year: 2023, month: 6, day: 15, hour: 14, minute: 30, region: .current) // Start and end of time periods let startOfDay = date.dateAt(.startOfDay) print(startOfDay.hour) // 0 let endOfDay = date.dateAt(.endOfDay) print(endOfDay.hour) // 23 print(endOfDay.minute) // 59 let startOfWeek = date.dateAt(.startOfWeek) let endOfWeek = date.dateAt(.endOfWeek) let startOfMonth = date.dateAt(.startOfMonth) let endOfMonth = date.dateAt(.endOfMonth) // Tomorrow and yesterday variations let tomorrow = date.dateAt(.tomorrow) let tomorrowAtStart = date.dateAt(.tomorrowAtStart) let yesterday = date.dateAt(.yesterday) let yesterdayAtStart = date.dateAt(.yesterdayAtStart) // Next/previous periods let nextMonth = date.dateAt(.nextMonth) let prevMonth = date.dateAt(.prevMonth) let nextWeek = date.dateAt(.nextWeek) let prevWeek = date.dateAt(.prevWeek) let nextYear = date.dateAt(.nextYear) let prevYear = date.dateAt(.prevYear) // Nearest time units let nearestMinute = date.dateAt(.nearestMinute(5)) // Round to nearest 5 minutes let nearestHour = date.dateAt(.nearestHour(3)) // Round to nearest 3 hours // Next weekday occurrence let nextFriday = date.dateAt(.nextWeekday(.friday)) print(nextFriday.weekdayNameShort) // "Fri" // DST transitions let nextDST = date.dateAt(.nextDSTTransition) // Altering time components let newTime = date.dateBySet(hour: 10, min: 0, secs: 0) print(newTime?.hour ?? 0) // 10 // Truncating components let dateOnly = date.dateTruncated(at: [.hour, .minute, .second]) print(dateOnly?.hour ?? 24) // 0 let truncatedFromHour = date.dateTruncated(from: .hour) print(truncatedFromHour?.minute ?? 30) // 0 // Rounding dates let rounded = date.dateRoundedAt(.to5Mins) let roundedCeil = date.dateRoundedAt(.toCeil10Mins) let roundedFloor = date.dateRoundedAt(.toFloor30Mins) // Adding components let nextYear2 = date.dateByAdding(1, .year) let nextMonth2 = date.dateByAdding(2, .month) let in5Days = date.dateByAdding(5, .day) // Date enumeration with custom increment let from = DateInRegion(year: 2023, month: 1, day: 1, hour: 10, region: .current) let to = DateInRegion(year: 2023, month: 1, day: 2, hour: 15, region: .current) let increment = DateComponents.create { $0.hour = 2 $0.minute = 30 } let dates = DateInRegion.enumerateDates(from: from, to: to, increment: increment) print(dates.count) // All dates incremented by 2h 30m // Get all Mondays in a month let mondaysInJan2023 = DateInRegion.datesForWeekday(.monday, inMonth: 1, ofYear: 2023, region: .current) print(mondaysInJan2023.count) // 4 or 5 depending on month ``` -------------------------------- ### Create Time Period Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/12.Timer_Periods.md Demonstrates how to initialize a TimePeriod with start and end dates, or with a start date and a duration. Requires the DateInRegion class. ```swift let toDate = DateInRegion().dateAtStartOf(.day) // now at 00:00 let fromDate = toDate - 3.days // 3 days ago at 00:00 let period = TimePeriod(start: fromDate , end: toDate) ``` ```swift let _ = TimePeriod(start: DateInRegion(), duration: 3.days) ``` -------------------------------- ### SwiftDate: Relative Date Formatting Examples Source: https://context7.com/malcommac/swiftdate/llms.txt Demonstrates various ways to format dates relative to the current time using SwiftDate. Includes Twitter-style, default styles, and localization for English and Italian. Also shows how to use a custom reference date for relative formatting. ```swift import SwiftDate // Twitter-style relative formatting let recent = Date() - 3.minutes let twitterStyle = recent.toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.english) print(twitterStyle) // "3m" let recentItalian = Date() - 6.minutes let twitterItalian = recentItalian.toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.italian) print(twitterItalian) // "6 min fa" // Default style relative formatting let now = DateInRegion() let fiveHoursAgo = now - 5.hours let defaultStyle = fiveHoursAgo.toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.english) print(defaultStyle) // "5 hours ago" let fortyMinutesAgo = now - 40.minutes let italianRelative = fortyMinutesAgo.toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.italian) print(italianRelative) // "40 minuti fa" // Various relative flavors let yesterday = now - 1.days print(yesterday.toRelative(style: RelativeFormatter.defaultStyle(), locale: .english)) // "yesterday" let nextWeek = now + 7.days print(nextWeek.toRelative(style: RelativeFormatter.defaultStyle(), locale: .english)) // "in 1 week" // Different flavors: .long, .longTime, .shortTime, .narrow, .tiny, .quantify let twoMonthsAgo = now - 2.months print(twoMonthsAgo.toRelative(style: RelativeFormatter.defaultStyle(), locale: .english)) // "2 months ago" // Relative formatting with custom reference date let referenceDate = DateInRegion(year: 2023, month: 6, day: 15, region: .current) let targetDate = DateInRegion(year: 2023, month: 6, day: 10, region: .current) let relativeStr = targetDate.toRelative(since: referenceDate, style: RelativeFormatter.defaultStyle(), locale: .english) // "5 days ago" (relative to referenceDate) ``` -------------------------------- ### Swift Derivated Dates and Date Manipulation Source: https://github.com/malcommac/swiftdate/blob/master/README.md Provides examples of generating derived dates and manipulating existing ones in Swift using the SwiftDate library. Functions include getting start/end of periods, altering time components, truncating, rounding, adding components, and enumerating dates within a range. ```swift let _ = DateInRegion().dateAt(.endOfDay) // today at the end of the day // Over 20 different relevant dates including .startOfDay, // .endOfDay, .startOfWeek, .tomorrow, .nextWeekday, .nextMonth, .prevYear, .nearestMinute and many others! let _ = dateA.nextWeekday(.friday) // the next friday after dateA let _ = (date.dateAt(.startOfMonth) - 3.days) let _ = dateA.compare(.endOfWeek) // Enumerate dates in range by providing your own custom // increment expressed in date components let from = DateInRegion("2015-01-01 10:00:00", region: rome)! let to = DateInRegion("2015-01-02 03:00:00", region: rome)! let increment2 = DateComponents.create { $0.hour = 1 $0.minute = 30 $0.second = 10 } // generate dates in range by incrementing +1h,30m,10s each new date let dates = DateInRegion.enumerateDates(from: fromDate2, to: toDate2, increment: increment2) // Get all mondays in Jan 2019 let mondaysInJan2019 = Date.datesForWeekday(.monday, inMonth: 1, ofYear: 2019) // Altering time components let _ = dateA.dateBySet(hour: 10, min: 0, secs: 0) // Truncating a date let _ = dateA.dateTruncated(at: [.year,.month,.day]) // reset all time components keeping only date // Rounding a date let _ = dateA.dateRoundedAt(.toMins(10)) let _ = dateA.dateRoundedAt(.toFloor30Mins) // Adding components let _ = dateA.dateByAdding(5,.year) // Date at the start/end of any time component let _ = dateA.dateAtEndOf(.year) // 31 of Dec at 23:59:59 let _ = dateA.dateAtStartOf(.day) // at 00:00:00 of the same day let _ = dateA.dateAtStartOf(.month) // at 00:00:00 of the first day of the month ``` -------------------------------- ### Shift Time Period Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/12.Timer_Periods.md Shows how to shift a TimePeriod forward or backward in time using the `shifted(by:)` method. This example creates a period for the current week and then shifts it by 7 days. ```swift // Create a time period at the start of the current week and end at the end of the week let fromDate = DateInRegion().dateAtStartOf([.weekOfYear,.day]) let toDate = fromDate.dateAtEndOf([.weekOfMonth,.day]) let thisWeek = TimePeriod(start: fromDate, end: toDate) // Shift the period by 7 days in the future let shiftedByOneWeek = thisWeek.shifted(by: 7.days) ``` -------------------------------- ### Swift Date Creation with Region (Timezone, Calendar, Locale) Source: https://github.com/malcommac/swiftdate/blob/master/README.md Illustrates how to create `DateInRegion` objects in Swift, which include timezone, calendar, and locale information. Examples show creation from strings, time intervals, date components, and random date generation. ```swift // All dates includes timezone, calendar and locales! // Create from string let rome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian) let date1 = DateInRegion("2010-01-01 00:00:00", region: rome)! // Create date from intervals let _ = DateInRegion(seconds: 39940, region: rome) let _ = DateInRegion(milliseconds: 5000, region: rome) // Date from components let _ = DateInRegion(components: { $0.year = 2001 $0.month = 9 $0.day = 11 $0.hour = 12 $0.minute = 0 }, region: rome) let _ = DateInRegion(year: 2001, month: 1, day: 5, hour: 23, minute: 30, second: 0, region: rome) // Random date generation with/without bounds let _ = DateInRegion.randomDate(region: rome) let _ = DateInRegion.randomDate(withinDaysBeforeToday: 5) let _ = DateInRegion.randomDates(count: 50, between: lowerLimitDate, and: upperLimitDate, region: rome) ``` -------------------------------- ### Configure AppDelegate Default Region in SwiftDate Source: https://github.com/malcommac/swiftdate/wiki/1.-Introduction:-Absolute-Date-and-DateInRegion Provides an example of how to set a specific default region (Rome, Italy) within the `application(_:didFinishLaunchingWithOptions:)` method of an AppDelegate. This ensures that all subsequent date operations in the application will automatically use the configured region, simplifying date management. ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Define a Region in Rome/Italy and set it as default region // Our Region also uses Gregorian Calendar and Italy Locale let romeRegion = Region(tz: TimeZoneName.europeRome, cal: CalendarName.gregorian, loc: LocaleName.italianItaly) Date.setDefaultRegion(romeRegion) // Since now each Date function works with this region instead of UTC return true } ``` -------------------------------- ### Create and Append Time Periods to a Collection (Swift) Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/12.Timer_Periods.md Demonstrates how to initialize a TimePeriodCollection and add TimePeriod objects to it. This involves creating individual time periods with specified start and end dates and then appending them as a group to the collection. Assumes the existence of 'toDate()' extension and 'SortType' enum. ```swift let collection = TimePeriodCollection() let firstPeriod = TimePeriod(start: "2014-11-05 18:15:12".toDate()!, end: "2015-11-05 18:20:12".toDate()!) let secondPeriod = TimePeriod(start: "2014-11-05 18:30:12".toDate()!, end: "2015-11-05 18:35:12".toDate()!) collection.append([firstPeriod,secondPeriod]) ``` -------------------------------- ### Lengthen Time Period Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/12.Timer_Periods.md Illustrates how to lengthen a TimePeriod using the `lengthened(by:at:)` method, anchoring either the start, end, or center. This example doubles a one-minute period. ```swift let oneMinutePeriod = TimePeriod(end: DateInRegion(), duration: 1.minutes) let lengthed = oneMinutePeriod.lengthened(by: 1.minutes.timeInterval, at: .end) ``` -------------------------------- ### Create Region SwiftDate Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/1.Introduction.md Demonstrates creating Region instances with specified calendar, timezone, and locale. These parameters define how dates are interpreted and displayed. ```swift let regionNY = Region(calendar: Calendars.gregorian, zone: Zones.americaNewYork, locale: Locales.englishUnitedStates) let regionTokyo = Region(calendar: Calendars.gregorian, zone: Zones.asiaTokyo, locale: Locales.japanese) ``` -------------------------------- ### Get Date After Specific Weeks in Swift Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/3.Manipulate_Date.md Calculates the date that falls on a specific weekday after a given number of weeks from a starting date. The time components (hour, minute, second) of the original date are preserved. This is useful for recurring date calculations. ```swift import SwiftDate let d = "2019-09-14 00:00".toDate("yyyy-MM-dd HH:mm", region: Region.current)! let nextTwoMondays = d.dateAfter(weeks: 2, on: .monday) // Calculates the date of the Monday two weeks later ``` -------------------------------- ### Create DateInRegion From Components SwiftDate Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/1.Introduction.md Creates a DateInRegion using date components. Supports initialization via a builder pattern or by passing individual components like year, month, day, hour, minute, and second. ```swift let date3 = DateInRegion(components: { $0.year = 2018 $0.month = 2 $0.day = 1 $0.hour = 23 }, region: regionNY) let date4 = DateInRegion(year: 2015, month: 2, day: 4, hour: 20, minute: 00, second: 00, region: regionNY) ``` -------------------------------- ### Swift Date Comparison with Granularity and Operators Source: https://github.com/malcommac/swiftdate/blob/master/README.md Demonstrates how to compare dates in Swift using standard math operators and advanced comparison functions with support for various granularities. It covers checking date ranges, relative dates, and using comparison functions for events. ```swift // Standard math comparison is allowed let _ = dateA >= dateB || dateC < dateB // Complex comparisons includes granularity support let _ = dateA.compare(toDate: dateB, granularity: .hour) == .orderedSame let _ = dateA.isAfterDate(dateB, orEqual: true, granularity: .month) // > until month granularity let _ = dateC.isInRange(date: dateA, and: dateB, orEqual: true, granularity: .day) // > until day granularity let _ = dateA.earlierDate(dateB) // earlier date let _ = dateA.laterDate(dateB) // later date // Check if date is close to another with a given precision let _ = dateA.compareCloseTo(dateB, precision: 1.hours.timeInterval // Compare for relevant events: // .isToday, .isYesterday, .isTomorrow, .isWeekend, isNextWeek // .isSameDay, .isMorning, .isWeekday ... let _ = date.compare(.isToday) let _ = date.compare(.isNight) let _ = date.compare(.isNextWeek) let _ = date.compare(.isThisMonth) let _ = date.compare(.startOfWeek) let _ = date.compare(.isNextYear) // ...and MORE THAN 30 OTHER COMPARISONS BUILT IN // Operation in arrays (oldestIn, newestIn, sortedByNewest, sortedByOldest...) let _ = DateInRegion.oldestIn(list: datesArray) let _ = DateInRegion.sortedByNewest(list: datesArray) ``` -------------------------------- ### Get Seconds Since Reference Date (Swift) Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/1.Introduction.md This snippet shows how to get the current date and print the number of seconds elapsed since the reference date (January 1, 2001, 00:00 UTC). This demonstrates the absolute time representation used by Cocoa's Date object. ```swift let now = Date() print("\(now.timeIntervalSinceReferenceDate) seconds elapsed since Jan 1, 2001 @ 00:00 UTC") ``` -------------------------------- ### Format Dates to Strings with SwiftDate Source: https://context7.com/malcommac/swiftdate/llms.txt This Swift code illustrates various methods for formatting DateInRegion objects into strings using SwiftDate. It covers standard format conversions (like DotNET, ISO, RSS, SQL), custom patterns, locale-aware formatting, predefined styles for date, time, and combined date-time, and formatting time intervals. ```swift import SwiftDate let london = Region(calendar: .gregorian, zone: .europeLondon, locale: .english) let date = DateInRegion("2017-07-22 18:27:02", format: "yyyy-MM-dd HH:mm:ss", region: london)! // Standard format conversions print(date.toDotNET()) // "/Date(1500740822000+0200)/" print(date.toISODate()) // "2017-07-22T18:27:02+02:00" print(date.toRSS(alt: false)) // RSS format print(date.toSQL()) // SQL format // Custom format with pattern print(date.toFormat("dd MMM yyyy 'at' HH:mm")) // "22 Jul 2017 at 18:27" // Change locale while formatting print(date.toFormat("dd MMM", locale: .italian)) // "22 Lug" print(date.toFormat("EEEE, MMMM dd, yyyy", locale: .french)) // French format // Predefined styles for date only print(date.toFormat(style: .date(.short))) // "7/22/17" print(date.toFormat(style: .date(.medium))) // "Jul 22, 2017" print(date.toFormat(style: .date(.long))) // "July 22, 2017" print(date.toFormat(style: .date(.full))) // "Saturday, July 22, 2017" // Predefined styles for time only print(date.toFormat(style: .time(.short))) // "6:27 PM" print(date.toFormat(style: .time(.medium))) // "6:27:02 PM" // Combined date and time print(date.toFormat(style: .dateTime(.short))) // "7/22/17, 6:27 PM" print(date.toFormat(style: .dateTime(.medium))) // "Jul 22, 2017, 6:27:02 PM" // Format time intervals as clock countdown let interval = (2.hours.timeInterval) + (34.minutes.timeInterval) + (5.seconds.timeInterval) print(interval.toClock()) // "2:34:05" // Format time intervals by components let formatted = interval.toIntervalString { $0.maximumUnitCount = 4 $0.allowedUnits = [.day, .hour, .minute] $0.collapsesLargestUnit = true $0.unitsStyle = .abbreviated } print(formatted) // "2h 34m" ``` -------------------------------- ### Add SwiftDate with Swift Package Manager Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/0.Informations.md Instructions for adding SwiftDate as a dependency using the Swift Package Manager (SPM). SwiftDate supports SPM on compatible platforms. Add the package URL and version to your Package.swift file. ```swift dependencies: [ .package(url: "https://github.com/malcommac/SwiftDate.git", from: "5.0.0") ] ``` -------------------------------- ### Get Time Period Relationship Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/12.Timer_Periods.md Demonstrates how to determine the relationship between two TimePeriod objects using the `relation(to:)` method, which returns a `TimePeriodRelation` enum value. ```swift let relationship = periodA.relation(to: periodB) ``` -------------------------------- ### Create DateInRegion From String SwiftDate Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/1.Introduction.md Initializes a DateInRegion by parsing a string with an optional format. SwiftDate reuses its parser for efficiency when handling multiple strings. ```swift let date1 = DateInRegion("2016-01-05", format: "yyyy-MM-dd", region: regionNY) let date2 = DateInRegion("2015-09-24T13:20:55", region: regionNY) ``` -------------------------------- ### Get Interval Between Dates in Swift Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/3.Manipulate_Date.md Calculates the interval between two DateInRegion objects, returning the difference as a specified Calendar.Component. This function is useful for determining time differences in hours, days, etc. ```swift let dateA = DateInRegion("2017-07-22 00:00:00", format: format, region: rome)! let dateB = DateInRegion("2017-07-23 12:00:00", format: format, region: rome)! let hours = dateA.getInterval(toDate: dateB, component: .hour) // 36 hours let days = dateA.getInterval(toDate: dateB, component: .day) // 1 day ``` -------------------------------- ### Work with Date Ranges and Periods using Swift Source: https://context7.com/malcommac/swiftdate/llms.txt Illustrates the creation and manipulation of `TimePeriod` objects in SwiftDate for representing date ranges. It covers initialization from start/end dates or durations, shifting, lengthening, shortening, and comparison operations. The `TimePeriod` class is essential for date range logic. ```swift import SwiftDate let start = DateInRegion(year: 2023, month: 1, day: 1, region: .current) let end = DateInRegion(year: 2023, month: 12, day: 31, region: .current) // Create time period from start and end let yearPeriod = TimePeriod(start: start, end: end) print(yearPeriod.duration ?? 0) // Duration in seconds // Create from start and duration let weekPeriod = TimePeriod(start: start, duration: 7.days) print(weekPeriod.end?.day ?? 0) // 7 days after start // Create from end and duration (duration subtracted from end) let monthPeriod = TimePeriod(end: end, duration: 30.days) print(monthPeriod.start?.month ?? 0) // December // Create from DateComponents duration let customPeriod = TimePeriod(start: start, duration: DateComponents.create { $0.month = 3 $0.day = 15 }) // Infinite period (distant past to distant future) let infinity = TimePeriod.infinity() print(infinity.hasStart && infinity.hasEnd) // true // Shift period by time interval let shifted = yearPeriod.shifted(by: 1.days.timeInterval) print(shifted.start?.day ?? 0) // 2 // Shift by components let shiftedByMonth = yearPeriod.shifted(by: 1.months) print(shiftedByMonth.start?.month ?? 0) // 2 // Lengthen period from different anchors let lengthenedFromEnd = yearPeriod.lengthened(by: 10.days.timeInterval, at: .end) // End date extends by 10 days let lengthenedFromBeginning = yearPeriod.lengthened(by: 5.days.timeInterval, at: .beginning) // Start date stays same, end extends let lengthenedFromCenter = yearPeriod.lengthened(by: 10.days.timeInterval, at: .center) // Both start and end extend // Shorten period let shortened = yearPeriod.shortened(by: 10.days.timeInterval, at: .end) // End date moves back 10 days // Check if date is in period let someDate = DateInRegion(year: 2023, month: 6, day: 15, region: .current) let isInPeriod = yearPeriod.contains(someDate, interval: .closed) print(isInPeriod) // true // Period overlap let period1 = TimePeriod(start: start, end: start + 30.days) let period2 = TimePeriod(start: start + 20.days, end: start + 50.days) let overlaps = period1.overlaps(with: period2) print(overlaps) // true // Period relationship let relation = period1.relation(to: period2) // Returns relationship type (overlaps, contains, etc.) // Operator overloads let extendedPeriod = yearPeriod + 5.days.timeInterval // Lengthen by 5 days let reducedPeriod = yearPeriod - 3.days.timeInterval // Shorten by 3 days ``` -------------------------------- ### Get Next Weekday in Swift Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/3.Manipulate_Date.md Calculates the next occurrence of a specific weekday, preserving the time components (hour, minute, seconds) of the original date. This function is useful for scheduling and time-based event planning. ```swift import SwiftDate let date1 = DateInRegion("2019-05-11 00:00:00", format: .iso8601, region: Region.Rome)! // Example date let nextFriday = date1.nextWeekday(.friday) // Returns the next Friday at 00:00:00 ``` -------------------------------- ### Create DateInRegion From Date SwiftDate Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/1.Introduction.md Initializes a DateInRegion directly from an existing `Date` object and a target region. This is useful for converting a system date into a SwiftDate object with specific regional context. ```swift let absoluteDate: Date = (Date() - 2.months).dateAt(.startOfDay) let date7 = DateInRegion(absoluteDate, region: regionNY) ``` -------------------------------- ### Get Colloquial String Since Now Source: https://github.com/malcommac/swiftdate/wiki/3.-Create-Dates Compares a date with the current date and returns a colloquial string representation of the interval (e.g., '2 hours ago', 'in 3 days'). The language used for the output is determined by the locale of the DateInRegion's Region. ```swift // Example 1 let d = DateInRegion(absoluteDate: Date() + 35.minute, in: region_rome) // a future date (+35 minutes from now) let d_str = try! x.colloquialSinceNow() // "tra 35 minuti" ``` -------------------------------- ### Enumerate Dates with Fixed Increment (Swift) Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/3.Manipulate_Date.md The `enumerateDates` function with a `DateComponents` increment allows for the generation of a list of dates starting from a `startDate` and ending before or at an `endDate`. Each subsequent date is calculated by adding the specified `increment` to the previous one. ```swift let increment = DateComponents.create { $0.hour = 1 $0.minute = 30 } let dates = DateInRegion.enumerateDates(from: fromDate, to: toDate, increment: increment) ``` -------------------------------- ### Generate Related Dates in Swift Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/3.Manipulate_Date.md Generates various related dates from a given date instance, such as the start of the day, next weekday, or previous month. It uses the `dateAt(_:)` function with a `DateRelatedType` enum. Input is a DateInRegion and a DateRelatedType, output is a DateInRegion. ```swift // Return today's datetime at 00:00:00 let _ = DateInRegion().dateAt(.startOfDay) // Return today's datetime at 23:59:59 let _ = DateInRegion().dateAt(.endOfDay) // Return the date at the start of this week let _ = DateInRegion().dateAt(.startOfWeek) // Return current time tomorrow let _ = DateInRegion().dateAt(.tomorrow) // Return the next sunday from specified date let _ = date.dateAt(.nextWeekday(.sunday)) // and so on... ``` -------------------------------- ### Format Relative Dates Swift Source: https://github.com/malcommac/swiftdate/blob/master/README.md Demonstrates the flexible relative date formatting capabilities of SwiftDate. It supports over 120 languages, different styles (e.g., .default, .twitter), and various flavors. Custom translations and rules can be provided for advanced customization. ```swift let _ = (Date() - 3.minutes).toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.english) // "3m" let _ = (Date() - 6.minutes).toRelative(style: RelativeFormatter.twitterStyle(), locale: Locales.italian) // "6 min fa" let _ = (now2 - 5.hours).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.english) // "5 hours ago" let y = (now2 - 40.minutes).toRelative(style: RelativeFormatter.defaultStyle(), locale: Locales.italian) // "45 minuti fa" ``` -------------------------------- ### Codable Support for DateInRegion and Region Swift Source: https://github.com/malcommac/swiftdate/blob/master/README.md Explains and demonstrates how `DateInRegion` and `Region` objects fully support Swift's `Codable` protocol. This allows for seamless encoding to and decoding from formats like JSON. ```swift // Encoding/Decoding a Region let region = Region(calendar: Calendars.gregorian, zone: Zones.europeOslo, locale: Locales.english) let encodedJSON = try JSONEncoder().encode(region) let decodedRegion = try JSONDecoder().decode(Region.self, from: encodedJSON) // Encoding/Decoding a DateInRegion let date = DateInRegion("2015-09-24T13:20:55", region: region) let encodedDate = try JSONEncoder().encode(date) let decodedDate = try JSONDecoder().decode(DateInRegion.self, from: encodedDate) ``` -------------------------------- ### Get Date at Start/End of Time Component (Swift) Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/3.Manipulate_Date.md These functions, `dateAtStartOf()` and `dateAtEndOf()`, allow you to obtain a new date instance set to the beginning or end of a specified calendar component (e.g., day, week, month, year) from an existing date. ```swift let endOfDay = DateInRegion().dateAtEndOf(.day) let startOfMonth = date1.dateAtStartOf(.month) let startOfYear = DateInRegion().dateAtStartOf(.year) ``` -------------------------------- ### Swift - SQL Date Formatting Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/5.Date_Formatting.md Converts a DateInRegion instance to a SQL formatted string. The output includes date, time, and milliseconds, along with the timezone offset. ```swift import SwiftDate let date = "2015-11-19T22:20:40+01:00".toISODate()! let sqlString = date.toSQL() // "2015-11-19T22:20:40.000+01" ``` -------------------------------- ### Format Dates Swift Source: https://github.com/malcommac/swiftdate/blob/master/README.md Illustrates various methods for formatting DateInRegion objects into strings. This includes using custom formats, predefined formats like .toDotNET() and .toISODate(), changing locale for formatting, and formatting time intervals as clock displays or component-based strings. ```swift let london = Region(calendar: .gregorian, zone: .europeLondon, locale: .english) let date = ... // 2017-07-22T18:27:02+02:00 in london region let _ = date.toDotNET() // /Date(1500740822000+0200)/ let _ = date.toISODate() // 2017-07-22T18:27:02+02:00 let _ = date.toFormat("dd MMM yyyy 'at' HH:mm") // "22 July 2017 at 18:27" let _ = date.toFormat("dd MMM", locale: .italian) // "22 Luglio" let interval: TimeInterval = (2.hours.timeInterval) + (34.minutes.timeInterval) + (5.seconds.timeInterval) let _ = interval.toClock() // "2:34:05" let _ = interval.toString { $0.maximumUnitCount = 4 $0.allowedUnits = [.day, .hour, .minute] $0.collapsesLargestUnit = true $0.unitsStyle = .abbreviated } // "2h 34m" ``` -------------------------------- ### Encode and Decode Dates and Regions with JSON using Swift Source: https://context7.com/malcommac/swiftdate/llms.txt Demonstrates how to encode and decode `DateInRegion` and `Region` objects to and from JSON using Swift's `Codable` protocol and `JSONEncoder`/`JSONDecoder`. It also shows how to integrate these into custom `Codable` structs. Dependencies include SwiftDate and Foundation. ```swift import SwiftDate import Foundation // Encoding/Decoding a Region let region = Region(calendar: Calendars.gregorian, zone: Zones.europeOslo, locale: Locales.english) do { // Encode region to JSON let encodedJSON = try JSONEncoder().encode(region) print(String(data: encodedJSON, encoding: .utf8) ?? "") // {"calendar":"gregorian","timezone":"Europe/Oslo","locale":"en"} // Decode region from JSON let decodedRegion = try JSONDecoder().decode(Region.self, from: encodedJSON) print(decodedRegion.timeZone.identifier) // "Europe/Oslo" print(decodedRegion.locale.identifier) // "en" } catch { print("Encoding/Decoding error: (error)") } // Encoding/Decoding a DateInRegion let date = DateInRegion("2015-09-24T13:20:55", format: "yyyy-MM-dd'T'HH:mm:ss", region: region)! do { // Encode date to JSON let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 let encodedDate = try encoder.encode(date) print(String(data: encodedDate, encoding: .utf8) ?? "") // Decode date from JSON let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let decodedDate = try decoder.decode(DateInRegion.self, from: encodedDate) print(decodedDate.year) // 2015 print(decodedDate.month) // 9 print(decodedDate.day) // 24 } catch { print("Date encoding/decoding error: (error)") } // Using in custom types struct Event: Codable { let title: String let startDate: DateInRegion let region: Region } let event = Event( title: "Conference", startDate: DateInRegion(year: 2023, month: 12, day: 1, region: region), region: region ) do { let eventJSON = try JSONEncoder().encode(event) let decodedEvent = try JSONDecoder().decode(Event.self, from: eventJSON) print(decodedEvent.title) // "Conference" } catch { print("Event error: (error)") } ``` -------------------------------- ### Get Date at Week Number/Weekday in Swift Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/3.Manipulate_Date.md Constructs a date based on a specified weekday ordinal, weekday, and month number, while preserving the hour, minute, and second components from the original date. This allows for precise date construction within a given month and year. ```swift import SwiftDate let date1 = DateInRegion("2019-05-11 00:00:00", format: .iso8601, region: Region.Rome)! // Example date let dateAtGivenWeekday = date1.dateAt(weekdayOrdinal: 3, weekday: .friday, monthNumber: date1.month + 1) // Example: 3rd Friday of the next month ``` -------------------------------- ### Date Components - Month Source: https://github.com/malcommac/swiftdate/wiki/2.-Date-Components Provides access to month-related components of a Date object. ```APIDOC ## Month Components ### `month` : `Int` Return the number of month units for the receiver. #### Discussion * For `DateInRegion` the value is interpreted in the context of the calendar of associated `Region`. * For `Date` the value is interpreted in the context of the Default Region set. ### `monthDays` : `Int` Return the number of days into the current month of the receiver. #### Discussion * For `DateInRegion` the value is interpreted in the context of the calendar of associated `Region`. * For `Date` the value is interpreted in the context of the Default Region set. ### `quarter` : `Int` Return the number of quarters for the receiver. #### Discussion * For `DateInRegion` the value is interpreted in the context of the calendar of associated `Region`. * For `Date` the value is interpreted in the context of the Default Region set. ### `monthName` : `String` Return the name of the current month for the receiver (ie. `March`). The language used is retrieved from the current region's locale. ``` -------------------------------- ### Parse Dates in Swift with Various Formats Source: https://github.com/malcommac/swiftdate/blob/master/README.md This snippet demonstrates how to parse date strings into Swift Date objects using default formats, custom formats, ISO8601, and other common variants like RSS, Alt RSS, .NET, SQL, and HTTP. It highlights the automatic recognition of standard formats and the flexibility to specify custom ones. ```swift // All default datetime formats (15+) are recognized automatically let _ = "2010-05-20 15:30:00".toDate() // You can also provide your own format! let _ = "2010-05-20 15:30".toDate("yyyy-MM-dd HH:mm") // All ISO8601 variants are supported too with timezone parsing! let _ = "2017-09-17T11:59:29+02:00".toISODate() // RSS, Extended, HTTP, SQL, .NET and all the major variants are supported! let _ = "19 Nov 2015 22:20:40 +0100".toRSS(alt: true) ``` -------------------------------- ### Check if Date is Inside a Range using SwiftDate Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/4.Compare_Dates.md The `.isInRange()` function checks if a given date falls within a specified start and end date. It supports inclusivity of bounds and allows defining the granularity for comparison, from nanoseconds up to years. This is useful for various date-based conditional logic. ```swift let lowerBound = DateInRegion("2018-05-31 23:00:00", format: dateFormat, region: regionRome)! let upperBound = DateInRegion("2018-06-01 01:00:00", format: dateFormat, region: regionRome)! let testDate = DateInRegion("2018-06-01 00:02:00", format: dateFormat, region: regionRome)! // return true, date is inside the hour granularity let _ = testDate.isInRange(date: lowerBound, and: upperBound, orEqual: true, granularity: .hour) ``` -------------------------------- ### Mixed Date/Time Formatting with dateTimeMixed Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/5.Date_Formatting.md Formats a date using a combination of specified date and time styles. This allows for flexible output by selecting different formatting levels for the date part and the time part, such as displaying a full date with no time. ```swift // Just print full date with no time let formatted = date.toString(.dateTimeMixed(dateStyle: .full, timeStyle: .none)) ``` -------------------------------- ### Extract Date Components Swift Source: https://github.com/malcommac/swiftdate/blob/master/README.md Demonstrates how to extract individual components (year, month, day, hour, etc.) from a DateInRegion object. Values are expressed in the date's region, respecting its timezone and locale. The inner absoluteDate can be used to get UTC values. ```swift let london = Region(calendar: .gregorian, zone: .europeLondon, locale: .italian) let date = DateInRegion("2018-02-05 23:14:45", format: dateFormat, region: london)! let _ = date.year // 2018 let _ = date.month // 2 let _ = date.monthNameDefault // 'Febbraio' as the locale is the to IT! let _ = date.firstDayOfWeek // 5 let _ = date.weekdayNameShort // 'Lun' as locale is the to IT ``` -------------------------------- ### Get Next Date Variations in Swift Source: https://github.com/malcommac/swiftdate/blob/master/Documentation/3.Manipulate_Date.md Provides three functions to determine the next date based on different criteria: `nextWeekday()` for the immediate next weekday, `nextWeekday(:withWeekOfMonth:andMonthNumber)` for a specific weekday within a specific week of the month, and `next(dayOfMonth:monthOfYear:)` for the next occurrence of a specific day of the month. ```swift import SwiftDate let date = DateInRegion() // Current date and time // Get the next weekday (e.g., next Monday) let nextMonday = date.nextWeekday(.monday) // Get a specific weekday in a specific week of the month let specificDate = date.nextWeekday(.friday, withWeekOfMonth: 2, andMonthNumber: date.month) // Get the next occurrence of a specific day of the month let next31st = date.next(dayOfMonth: 31, monthOfYear: date.month) ``` -------------------------------- ### Convert Dates Between Regions with SwiftDate Source: https://context7.com/malcommac/swiftdate/llms.txt This Swift code demonstrates how to create date objects associated with specific regions (defined by calendar, timezone, and locale) and convert them to other regions. It shows conversions of individual attributes like timezone or locale, as well as mixed conversions. ```swift import SwiftDate // Create regions for different locations let rNY = Region(calendar: Calendars.gregorian, zone: Zones.americaNewYork, locale: Locales.english) let rRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian) // Create date in New York timezone let dateInNY = "2017-01-01 00:00:00".toDate(region: rNY)! print(dateInNY.toString()) // Shows NY time // Convert to Rome timezone let dateInRome = dateInNY.convertTo(region: rRome) print(dateInRome.toString()) // "dom gen 01 06:00:00 +0100 2017" (6 hours ahead) // Convert individual region attributes let dateInIndia = dateInNY.convertTo(timezone: Zones.indianChristmas, locale: Locales.nepaliIndia) print(dateInIndia.toString()) // Nepali locale with India timezone // Convert just timezone let londonDate = dateInNY.convertTo(timezone: .europeLondon) // Convert just locale let frenchDate = dateInNY.convertTo(locale: .french) print(frenchDate.monthNameDefault) // French month name // Convert just calendar let hebrewDate = dateInNY.convertTo(calendar: .hebrew) // Mix conversions let converted = dateInNY.convertTo( calendar: .gregorian, timezone: .asiaTokyo, locale: .japanese ) print(converted.toString()) // Japanese locale, Tokyo time ``` -------------------------------- ### Initialize DateInRegion from Time Components Source: https://github.com/malcommac/swiftdate/wiki/3.-Create-Dates Creates a new DateInRegion by specifying individual time components. Unspecified components default to 0 or are ignored. Requires a Region object to define the time zone, calendar, and locale. ```swift let region_rome = Region(tz: TimeZoneName.europeRome, cal: CalendarName.gregorian, loc: LocaleName.italianItaly) let d = DateInRegion(components: [.year:2010, .month:1, .day:4, .hour:20], fromRegion: region_rome) ```