SwiftDate Documentation

repository·master·Indexed 27 days ago

https://github.com/malcommac/swiftdate

A comprehensive toolkit for date and time manipulation in Swift, compatible with Apple platforms, Linux, and server-side Swift frameworks like Vapor or Kitura. SwiftDate provides an intuitive API for parsing, validating, comparing, and formatting dates and timezones. Key features include support for ISO8601 and custom formats, math operations using time units, relative date formatting in over 120 languages, and the use of Region and DateInRegion for geographic and cultural context management.

Tokens
16.1K
Snippets
55
Records
77
Agent score
93%

What's inside SwiftDate

  1. Overview of SwiftDate capabilities

    master

    SwiftDate is a toolkit for parsing, validating, manipulating, comparing, and displaying dates, time, and timezones in Swift. It is compatible with all Apple platforms, Linux, and Swift Server Side frameworks like Vapor or Kitura.

    Key features include:

    • Date Parsing: Supports custom formats, ISO8601, RSS, and more.
    • Date Formatting: Supports colloquial formatters and over 140 languages.
    • Date Manipulation: Perform math operations using time units (e.g., 2.hours + 5.minutes).
    • Component Extraction: Extract intuitive components like day, hour, nearestHour, or weekdayNameShort.
    • Derived Dates: Generate dates like nextWeek, nextMonth, nextWeekday, or tomorrow.
    • Date Comparison: Over 20 fine-grained functions such as isToday, isTomorrow, isSameWeek, and isNextYear.
    • Codable Support: Full support for Swift's Codable protocol.
    • Random Dates: Generation of random date objects.
    • Time Periods: Support for time period calculations and conversions (e.g., 2.hours.toUnits(.minutes)).
  2. Understand Region and DateInRegion

    master

    SwiftDate uses two primary structs to manage dates in specific geographic or cultural contexts:

    • Region: Defines a specific context using a TimeZone, a Locale, and a Calendar.
    • DateInRegion: Represents an absolute date within a specific Region. When using DateInRegion, all date components (like year, month, hour) are evaluated according to the rules of its associated region. It contains an absoluteDate property and a region property.
  3. Restore SwiftDate 4.x default region behavior

    master

    In SwiftDate 5.x and later, the default region's timezone is set to GMT+0 (UTC) to comply with Date's default behavior. In SwiftDate 4.x, the default region was automatically set to the local region (device's locale, timezone, and calendar).

    To restore the old behavior where the library uses the device's local settings, set SwiftDate.defaultRegion to Region.local during app launch.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    	SwiftDate.defaultRegion = Region.local // set region to local device attributes
    	// ... do something else
    	return true
    }
  4. Install SwiftDate via CocoaPods

    master

    To integrate SwiftDate into your Xcode project using CocoaPods, add the following to your Podfile. Note that CocoaPods 1.1+ is required.

    source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, '10.0'
    use_frameworks!
    
    target '<Your Target Name>' do
      pod 'SwiftDate', '~> 5.0'
    end

    After updating your Podfile, run pod install in your terminal.

  5. Add and subtract time units from a Date

    master

    SwiftDate extends the Int type to allow intuitive date arithmetic using readable time units. You can add or subtract these units from a Date or DateInRegion using standard math operators (+ and -).

    Supported time units include:

    • nanoseconds
    • seconds
    • minutes
    • hours
    • days
    • weeks
    • months
    • quarters
    • years

    Note: These values are automatically converted to DateComponents and evaluated using the target Date or DateInRegion's calendar context.

    let oneYearAhead = DateInRegion() + 1.years
    let someMinutesAgo = date1 - 2.minutes
    let fancyDate = date1 + 3.hours - 5.minutes + 1.weeks
  6. Configure the Default Region for Date operations

    master

    By default, SwiftDate uses a Default Region with GMT timezone, the device's current calendar, and the device's current locale.

    You can change the global default region for all Date instances (affecting parsing and component evaluation) by setting SwiftDate.defaultRegion.

    Note: It is recommended to use DateInRegion instances instead of changing the global default to ensure explicit region handling.

    let rome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
    SwiftDate.defaultRegion = rome
    
    // Now all Date extensions use the Rome region
    let dateInRome = "2018-01-01 00:00:00".toDate()!
    print("Current year is \(dateInRome.year) and hour is \(dateInRome.hour)") // "Current year is 2018 and hour is 0\n"
  7. Get the interval between two dates

    master

    Use the .getInterval(toDate:component:) function to calculate the difference between two dates expressed in a specific Calendar.Component (e.g., hours, days).

    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
  8. Enumerate dates in an interval

    master

    Generate a list of dates within a range using enumerateDates:

    • Fixed Increment: Pass a DateComponents object to increment each date by a constant amount.
    • Variable Increment: Pass a closure that takes the current DateInRegion and returns the next DateComponents increment.
    let increment = DateComponents.create { 
      $0.hour = 1
      $0.minute = 30
    }
    
    // Generates an array of dates starting from fromDate, 
    // incrementing by 1h30m until toDate is reached.
    let dates = DateInRegion.enumerateDates(from: fromDate, to: toDate, increment: increment)