SwiftDate ЁЯРФ Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift.

Overview

SwiftDate

Toolkit to parse, validate, manipulate, compare and display dates, time & timezones in Swift.

What's This?

SwiftDate is the definitive toolchain to manipulate and display dates and time zones on all Apple platform and even on Linux and Swift Server Side frameworks like Vapor or Kitura.
Over 3 million of downloads on CocoaPods.

From simple date manipulation to complex business logic SwiftDate maybe the right choice for your next project.

  • Easy Date Parsing (custom formats, iso8601, rss & many more)
  • Easy Date Formatting even with colloquial formatter and 140+ supported languages
  • Easy math operations with time units (2.hours + 5.minutes...)
  • Intuitive components extraction (day, hour, nearestHour, weekdayNameShort etc.)
  • Derivated dates generation (nextWeek, nextMonth, nextWeekday, tomorrow...)
  • Over 20+ fine grained date comparison functions (isToday, isTomorrow, isSameWeek, isNextYear...)
  • Swift 4's Codable Support
  • Random dates generation
  • Fine grained date enumeration functions
  • Time period support
  • Convert TimeIntervals to other units (2.hours.toUnits(.minutes))

and of course...

  • IT'S TESTED!. As 5.x the project has 90% of code coverage (want help us? write some unit tests and make a PR)
  • IT'S FULLY DOCUMENTED!, both with a complete guide and with Jazzy!
  • WE LOVE PLAYGROUND! Check out our interactive playground!

Start with SwiftDate

The entire library is fully documented both via XCode method inspector and a complete markdown documentation you can found below.

Explore SwiftDate

From simple date manipulation to complex business logic SwiftDate maybe the right choice for your next project.

Let me show to you the main features of the library:

1. Date Parsing

SwiftDate can recognize all the major datetime formats automatically (ISO8601, RSS, Alt RSS, .NET, SQL, HTTP...) and you can also provide your own formats. Creating a new date has never been so easy!

// 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)

2. Date Manipulation

Date can be manipulated by adding or removing time components using a natural language; time unit extraction is also easy and includes the support for timezone, calendar and locales!

Manipulation can be done with standard math operators and between dates, time intervals, date components and relevant time units!

1 ">
// Math operations support time units
let _ = ("2010-05-20 15:30:00".toDate() + 3.months - 2.days)
let _ = Date() + 3.hours
let _ = date1 + [.year:1, .month:2, .hour:5]
let _ = date1 + date2
// extract single time unit components from date manipulation
let over1Year = (date3 - date2).year > 1

3. Date Comparison

SwiftDate include an extensive set of comparison functions; you can compare two dates by granularity, check if a date is an particular day, range and practically any other comparison you ever need.

Comparison is also available via standard math operators like (>, >=, <, <=).

// 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)

4. Date Creation with Region (Timezone, Calendar & Locale)

You can create new dates from a string, time intervals or using date components. SwiftDate offers a wide set of functions to create and derivate your dates even with random generation!

// 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)

5. Derivated Dates

Date can be also generated starting from other dates; SwiftDate includes an extensive set of functions to generate. Over 20 different derivated dates can be created easily using dateAt() function.

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

6. Components Extraction

You can extract components directly from dates and it includes the right value expressed in date's region (the right timezone and set locale!).

// Create a date in a region, London but with the lcoale set to IT
let london = Region(calendar: .gregorian, zone: .europeLondon, locale: .italian)
let date = DateInRegion("2018-02-05 23:14:45", format: dateFormat, region: london)!

// You can extract any of the all available time units.
// VALUES ARE EXPRESSED IN THE REGION OF THE DATE (THE RIGHT TIMEZONE).
// (you can still get the UTC/absolute value by getting the inner's absoluteDate).

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
// ... all components are supported: .year, .month, .day, .hour, .minute, .second,
// .monthName, .weekday, .nearestHour, .firstDayOfWeek. .quarter and so on...

7. Switch between timezones/locale and calendars

You can easily convert any date to another region (aka another calendar, locale or timezone) easily! New date contains all values expressed into the destination reason

// Conversion between timezones is easy using convertTo(region:) function
let rNY = Region(calendar: Calendars.gregorian, zone: Zones.americaNewYork, locale: Locales.english)
let rRome = Region(calendar: Calendars.gregorian, zone: Zones.europeRome, locale: Locales.italian)
let dateInNY = "2017-01-01 00:00:00".toDate(region: rNY)
let dateInRome = dateInNY?.convertTo(region: rRome)!
print(dateInRome.toString()) // "dom gen 01 06:00:00 +0100 2017\n"

// You can also convert single region's attributes
let dateInIndia = dateInNY?.convertTo(timezone: Zones.indianChristmas, locale: Locales.nepaliIndia)
print("\(dateInIndia!.toString())") // "рдЖрдЗрдд рдЬрдирд╡рд░реА режрез резреи:режреж:режреж +0700 реирежрезрен\n"

8. Date Formatting

Date formatting is easy, you can specify your own format, locale or use any of the provided ones.

// Date Formatting
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"

// You can also easily change locale when formatting a region
let _ = date.toFormat("dd MMM", locale: .italian) // "22 Luglio"

// Time Interval Formatting as Countdown
let interval: TimeInterval = (2.hours.timeInterval) + (34.minutes.timeInterval) + (5.seconds.timeInterval)
let _ = interval.toClock() // "2:34:05"

// Time Interval Formatting by Components
let _ = interval.toString {
	$0.maximumUnitCount = 4
	$0.allowedUnits = [.day, .hour, .minute]
	$0.collapsesLargestUnit = true
	$0.unitsStyle = .abbreviated
} // "2h 34m"

9. Relative Date Formatting (fully customizable!)

Relative formatting is all new in SwiftDate; it supports 120+ languages with two different styles (.default, .twitter), 9 flavours (.long, .longTime, .longConvenient, .short, .shortTime, .shortConvenient, .narrow, .tiny, .quantify) and all of them are customizable as you need. The extensible format allows you to provide your own translations and rules to override the default behaviour.

// Twitter Style
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"

// Default Style
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"

10. Codable Support

Both DateInRegion and Region fully support the new Swift's Codable protocol. This mean you can safely encode/decode them:

// 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)

11. Time Periods

SwiftDate integrates the great Matthew York's DateTools module in order to support Time Periods.

See Time Periods section of the documentation.

Comments
  • Super slow compiling when archiving 6.0.1 Xcode 10.2

    Super slow compiling when archiving 6.0.1 Xcode 10.2

    When using Xcode 10.2 to archive my project, all pods go super fast but SwiftDate takes a lot of time (like 30 minutes). This didn't used to happen with Xcode 10.1 and SwiftDate 5.1.0. Any ideas?

    bug 
    opened by ripventura 26
  • Support for relative/pretty date formatting

    Support for relative/pretty date formatting

    Is there the way to custom┬аtime unit when call the function like toRelativeString? , and then return the relative representation with custom time unit. For example if the time unit is day, a relative representation of the date by comparing 2015-11-15 00:00 to the 2015-11-16 02:00 should be returned 1 day, and if the time unit is hour, should be returned 26 hours.

    enhancement 
    opened by xiajinchun 22
  • Misunderstanding how date components works with timezone and time calculations

    Misunderstanding how date components works with timezone and time calculations

    First, thank you for good library.

    I am very stupid with dates, maybe you can explain me what i miss.

    let justDate = NSDate()
    let localDate = NSDate().toLocalTime()
    let hongkongDate = NSDate().toTimezone("HKT")!
    let westEurDate = NSDate().toTimezone("MSK")!
    let futureDate = justDate + 4.hour
    
    L.d("justDate: \(justDate) (\(justDate.hour) : \(justDate.minute))")
    L.d("localDate: \(localDate) (\(localDate.hour) : \(localDate.minute))")
    L.d("hongkongDate: \(hongkongDate) (\(hongkongDate.hour) : \(hongkongDate.minute))")
    L.d("westEurDate: \(westEurDate) (\(westEurDate.hour) : \(westEurDate.minute))")
    L.d("futureDate: \(futureDate) (\(futureDate.hour) : \(futureDate.minute))")
    

    Output is strange for me.

    justDate: 2015-10-20 18:53:47 +0000 (21 : 53) localDate: 2015-10-20 15:53:47 +0000 (18 : 53) hongkongDate: 2015-10-21 02:53:47 +0000 (5 : 53) westEurDate: 2015-10-20 21:53:47 +0000 (0 : 53) futureDate: 2015-10-20 22:53:47 +0000 (1 : 53)

    This code was run on iPhone, not simulator. Real local time in time zone MSK was 21:53

    Minutes are save in every case. Hours different, but has wrong values, as i see.

    The target of this experiment is get hours and minutes of date in specific timezone.

    What i am doing wrong?

    opened by roma86 16
  • Carthage Bootstrap Error

    Carthage Bootstrap Error

    Just tried to integrate SwiftDate through Carthage, and hit this error after running carthage update:

    xcodebuild: error: Scheme SwiftDate-iOS is not currently configured for the build action.
    
    opened by reallyseth 15
  • toDate(_: ) return value wrong

    toDate(_: ) return value wrong

    Hey guy, if you try the follow code, date is "1986-03-02 23:00:00 +0000" instead of nil.

    let date = "31/02/1986".toDate(DateFormat.Custom("dd/MM/yyyy"))
    

    The follow code is how the date should be checked:

    func toDate(format: String = "yyyy-MM-dd'T'HH:mm") -> NSDate? {
       let dateFormatter = NSDateFormatter()
       dateFormatter.dateFormat = format
       return dateFormatter.dateFromString(self)
    }
    
    enhancement 
    opened by carmelogallo 14
  • DateFormatter: dealing with time interval formatting in SwiftDate

    DateFormatter: dealing with time interval formatting in SwiftDate

    Recently there was a discussion about the opportunity to use NSDateComponentsFormatter class in order to provide a string representation (both colloquial and by time unit components) of the interval between two dates. You can learn more about it starting here.

    In the meantime we belive it's good to provide an similar alternative; this is what we are doing in TimeIntervalFormatter gitflow feature of the develop branch (planned to go live for 3.1 release). The main class is called DateFormatter (link to commit) and allows you to print date interval in 5 different styles:

    TIME INTERVAL COMPONENTS STYLES

    • Positional (A style that uses the position of a unit to identify its value and commonly used for time values where components are separated by colons . "1:10:00")
    • Abbreviated (The abbreviated style represents the shortest spelling for unit values."1h 10m")
    • Short (A style that uses the short spelling for units.тАЬ1hr 10minтАЭ)
    • Full (A style that spells out the units fully. тАЬ1 hour, 10 minutesтАЭ)
    • Colloquial (For some relevant intervals this style print out a more colloquial string representation ("last month", "on 2016", "next year", "in 5 minutes", "just now" and so on).

    DateFormatter CLASS DateFormatter class allows you to specify several attributes used to customise the output string:

    • unitsStyle allows you to specify the string length used to print each time component (described above)
    • allowedUnits specify what kind of time units (seconds,hours,minutes...) maybe part of the output stirng (some units maybe dropped if zero, depending of zeroBehaviour parameter).
    • maxUnitCount if not nil specify the max number of time components used to compose the output string (from the high ordered time unit - year - to the smallest one, second). This value is not used for .Colloquial style.
    • zeroBehavior specify how to threat time units with zero values (should be included in the output string? how?). Possible values are .None (None, it does not remove components with zero values), .DropLeading (Units whose values are 0 are dropped starting at the beginning of the sequence until the first non-zero component), .DropMiddle ( Units whose values are 0 are dropped from anywhere in the middle of a sequence.), .DropTrailing (Units whose value is 0 are dropped starting at the end of the sequence back to the first non-zero component) and .DropAll. This param is not used for .Colloquial style.
    • includeRelevantTime this parameter is valid only for .Colloquial style. If specified for each interval of time (in years, in hours, in seconds...) a relevant time string will be added at the end of the output. For example for colloquial representation "in 2 hours" the final string maybe "in 2 hours (at 21:30)".
    • allowsNowOnColloquial this paramter is valid only for .Colloquial style. If specified for a time interval < 5 minutes the output will be "just now"

    Public methods of the class are:

    • public func toString(interval: NSTimeInterval) -> String?
    • public func toString(fromDate f: DateInRegion, toDate t: DateInRegion) -> String?

    .strings FILE SPECS The localized strings (at this time only en was created) are contained inside SwiftDate.bundle bundle. The file itself is documented, but basically it contains:

    • unit names strings (unitname_): how to spell years/minutes/seconds... in .Positional,.Short... styles)
    • colloquial strings (colloquial_): representation of the colloquial strings for each relevant amount of time
    • relevant time strings (relevanttime_): specify the date string format to add for each relevant variant
    • value separator (valuesep_): specify the separator string between each time unit in each style
    • unit separator (unitsep_) specify the separator string between each time unit component

    Codes for languages.

    COLLOQUIAL REPRESENTATION TABLE

    This is the logic used when you want to print a colloquial representation of the differences between two dates.

    | TIME DIFFERENCE | FUTURE | PAST | RELEVANT TIME | | --- | --- | --- | --- | | = 1 year | next year | last year | (Feb 2016) | | > 1 year | on 2016 | 2016 | (Feb 2016) | | = 1 month | next month | past month | (Feb 17, 2016) | | > 1 month | in 3 months | 3 months ago | (Feb 17, 2016) | | = 1 week | next week | past week | Wed, Feb 17 2016) | | > 1 week | in 3 weeks | 3 weeks ago | Wed, Feb 17 2016) | | = 1 day | tomorrow | yesterday | Wed, Feb 17 2016) | | > 1 day | in 2 days | 2 days ago | Wed, Feb 17 2016) | | = 1 hour | in one hour | one hour ago | (at 13:20) | | > 1 hour | in 3 hours | 3 hours ago | (at 13:20) | | = 1 minute | in one minute | one minute ago | none | | > 1 minute | in 3 minutes | 3 minutes ago | none | | < 5 minutes | just now | just now | none | | = 1 second | in one second | one second ago | none | | > 1 second | in 3 seconds | 3 seconds ago | none |

    I would also add special today time ranges:

    • today between 00:00 -> 06:00 -> this night (relevant time is the hour 'HH:mm')
    • today between 06:00 -> 12:00 -> this morning (relevant time is the hour 'HH:mm')
    • today between 12:00 -> 18:00 -> this afternoon (relevant time is the hour 'HH:mm')
    • today between 18:00 -> 24:00 -> this evening (relevant time is the hour 'HH:mm')

    I'll add it very soon but it should be enough to start first tests. cc @Hout

    enhancement design 
    opened by malcommac 14
  • Set WeekFirstDay not working version 5.1.0

    Set WeekFirstDay not working version 5.1.0

            var cal = Calendar.current
            cal.firstWeekday = 2 // 2 represents Monday
            cal.timeZone = Zones.gmt.toTimezone()
            cal.locale = Locales.englishUnitedStates.toLocale()
    

    I would like to set the week first day as Monday but the above which worked in swift 4 is not working after migrating to swift 4.2. So, Kindly can you check it once.

    question 
    opened by sathishvgs 12
  • Fix for NSRange under XCode 9 for 4.4.0 tagged release

    Fix for NSRange under XCode 9 for 4.4.0 tagged release

    [...]/Pods/SwiftDate/Sources/SwiftDate/DOTNETDateTimeFormatter.swift:47:90: Cannot call value of non-function type 'NSRange' (aka '_NSRange')

    [...]/Pods/SwiftDate/Sources/SwiftDate/DOTNETDateTimeFormatter.swift:50:66: Cannot call value of non-function type 'NSRange' (aka '_NSRange')

    bug 
    opened by daerimin 12
  • Add Region.defaultRegionProvider and defaultRegion()

    Add Region.defaultRegionProvider and defaultRegion()

    I found that recently defaultRegion is removed, after writing this patch..... But I think it is necessary for following reasons:

    • To cache Region object to get rid of overhead of NSCalendar initialization.
    • Currently tests depending on default locale fail in non-English locale machine.

    It could be implemented as built-in caching mechanism, but provider enables to controll cache storage and lifecycle by library user.

    Caching example

    Region.defaultRegionProvider = {
        if let cachedRegion = NSThread.currentThread().threadDictionary[kCacheKey] {
            return cachedRegion
        }
        let region = Region(...)
        NSThread.currentThread().threadDictionary[kCacheKey] = region
        return region
    }
    
    enhancement design 
    opened by ypresto 12
  • Value of type 'String.Index' has no member 'utf16Offset'

    Value of type 'String.Index' has no member 'utf16Offset'

    When trying to compile to virtual device

    /Pods/SwiftDate/Sources/SwiftDate/Foundation+Extras/TimeInterval+Formatter.swift:106:64: Value of type 'String.Index' has no member 'utf16Offset'

    if let index = formattedValue.firstIndex(of: ":"), index.utf16Offset(in: formattedValue) < 2 {

    XCode Version 10.1 (10B61)

    opened by julianfe 11
  • New ColloquialDateFormatter class (was colloquialSinceNow is incorrect)

    New ColloquialDateFormatter class (was colloquialSinceNow is incorrect)

    Hi! I use SwiftDate version 4.4.1. I use the colloquialSinceNow function for example the current time is 4:05, the event time was at 4:00, but this function returns "just now". How can I achieve the result in one minute without changing the framework? Thank you date.colloquialSinceNow(unitStyle: .full).colloquial

    bug enhancement 
    opened by alexanderkhitev 11
  • Why the last version 7.0.0 not support iOS12я╝Я

    Why the last version 7.0.0 not support iOS12я╝Я

    Hello, I upgraded the latest version 7.0.0 to fix lang error prompts, but found that iOS12 is no longer supported. Must I discard iOS12? Can I continue to support iOS12?

    opened by xuchuandong 0
  • SwiftDate langs folder contains a project?

    SwiftDate langs folder contains a project?

    Every time I compile, I get the following error:

    /Users/bentley/Library/Developer/Xcode/DerivedData/myproject-bhvokhypypgooyfufngrjsmjjohq/SourcePackages/checkouts/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/langs Couldn't load project at: /Users/bentley/Library/Developer/Xcode/DerivedData/myproject-bhvokhypypgooyfufngrjsmjjohq/SourcePackages/checkouts/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/langs

    That folder contains quite a few .json files.

    I removed and reinstalled the package with no apparent improvement.

    opened by crenelle 1
  • Remove resources param on SPM target

    Remove resources param on SPM target

    There is a resources param on the SwiftDate target definition. However, those resources were removed since version 7.0.0. Because of this param, SPM resolution of this library is not working with Tuist SPM Dependencies - Tuist denies this library due to missing resources.

    Removing resources param makes Tuist work with this library.

    opened by salqueng 0
  • Is there a type representing a

    Is there a type representing a "Date" as we use it in normal conversations--i.e. without time?

    Joda-time has the notion of a LocalDate, which is date without time; basically, what we mean by date in normal day-to-day English. I'm wondering if the SwiftDate library has it.

    I dug around a bit and am 99% sure there isn't, but just to be sure. If there isn't, do you guys have any plans to support it?

    Thank you :)

    opened by funct7 2
  • Is there a way to format Date with specific timezone?

    Is there a way to format Date with specific timezone?

    As mentioned in the doc's date formatting section, we can specific a locale to affect the style of formatting. But can we also specific a timezone used when formatting?

    // Maybe feasible solution
    
    let date = Date() // 2022-08-16 16:06:26 +0000
    let formattedInCurrentTimeZone = date.toFormat("yyyy-MM-dd HH:mm:ssZZZZZ") // current time zone, CST. 2022-08-17 00:06:26+0800
    let formattedInEST = date.toFormat("yyyy-MM-dd HH:mm:ssZZZZZ", timezone: .init("EST")) // 2022-08-16 12:06:26-0400
    

    When formatting a Date, timezone is a required arguments since Date is a wrapper of timestamp which is an absolute value, however if we format the Date to a String, we need consider the timezone since a String representing a Date is a relative value. The locale and timezone could be different on a device. So we can not infer timezone from locale.

    Thanks.

    opened by kyleduo 0
Releases(7.0.0)
  • 7.0.0(Sep 12, 2022)

    Released on 2022-09-12

    CHANGES

    • Removed RelativeTimeFormatter and replaced with built-in system class
    • Fixed compatibility issues on SPM

    This version require at least Swift 5.5, iOS 13+, macOS 10.15+, watchOS 6+, tvOS 13+.

    Source code(tar.gz)
    Source code(zip)
  • 6.3.1(Nov 22, 2020)

  • 6.3.0(Nov 15, 2020)

    Released on: 2020-11-16

    CHANGES

    • #753 [NEW]: Added added .dateMixed format options to toString() method to format dateTime with differing date and time styles.
    • #751 [NEW]: Added support for SPM 5.3 and Package.swift to support Xcode 12 and iOS9+.
    • #728 [NEW]: Added support Swift Package .automatic, .static and .dynamic linking support in order to share same package between multiple targets.
    • #727 [NEW] Added .asLocale() to String object to transform identifier in an NSLocale objectS.
    • #762 [FIX]: CocoaPods: Update podspec to iOS9 in order to fix Xcode 12 warning.
    • #760 [FIX]: Minor fixes to documentation and updated to 6.3.0.
    • #752 [FIX]: Avoid force unwrap in sharedOrdinalNumberFormatter.
    Source code(tar.gz)
    Source code(zip)
  • 6.2.0(Sep 16, 2020)

    Released on: 2020-09-16

    CHANGES

    • [NEW #694] Added support forDate position between 2 dates range (positionInRange)
    • [NEW #695] Added support for Swift Package Manager (SwiftPM) 5.1
    • [NEW #742] Added support for non latin Serbian localization
    • [FIX #749] Fixed a crash with force unwrap in TimeInterval+Formatter
    • [FIX #726] Fixed date comparison using the .isSameMonth option
    • [FIX #725] Fixed wrong timezone while setup a different SwiftDate.defaultRegion
    • [FIX #710] Fixed grammar for Slovak translation
    • [FIX #708] Fix typo in customFormatter of DataRepresentable
    • [FIX #707] Fixes traditional Chinese translation
    • [FIX #700] Fixed wrong behavior of dateAt(.startOfMonth)
    Source code(tar.gz)
    Source code(zip)
  • 6.1.0(Sep 14, 2019)

    Released on: 2019-09-13

    CHANGES

    • #682 - [FIX] Fixed Japanese relative datetime formatting.
    • #693 - [FIX] Fixed wrong result when subtracting DateInRegion dates.
    • #676 - [NEW] Added difference() and differences() methods to get the difference between two dates expressed in variuous time components with respect to the other date as a positive integer.
    • #676 - [NEW] Added dateAt(dayOfMonth:monthNumber:yearNumber:) method to returns the date on the given day of month preserving smaller components.
    • #676 - [NEW] Added dateAfter(weeks:on:) method to returns the date after given number of weeks on the given day of week.
    • #676 - [NEW] Added next(:withWeekOfMonth:andMonthNumber:) method to returns next date with the given weekday and the given week number.
    • #676 - [NEW] Added next(dayOfMonth:monthOfYear:) method to returns the next day of month preserving smaller components (hour, minute, seconds).
    Source code(tar.gz)
    Source code(zip)
  • 6.0.3(May 11, 2019)

    Released on: 2019-05-12

    CHANGES

    • #670 [FIX] FixedtoISODate() which ignores explicitly passed Region instance. Now if region is passed it overrides any parsed timezone from ISO source string.
    • #668 [FIX] Fixed missing zero padding with toClock() on the first digit.
    • #652 [FIX] Resolved slow compiling times: moved RelativeFormatter's languages files to json. This currently breaks Linux compatibility because SPM does not support bundled resources.
    • #666 [NEW] Added dateAt(weekdayOrdinal:weekday:monthNumber:yearNumber:) nextWeekday() to both Date and DateInRegion
    Source code(tar.gz)
    Source code(zip)
  • 6.0.2(Apr 16, 2019)

    Released on: 2019-04-16

    Changes

    • #656 Fixed for ISOFormatter options withoutTZSeparators which produces empty string results if not paired with withInternetDateTimeExtended
    • #653 TimeInterval.ComponentsFormatterOptions reverted to public visibility
    • #635 Better handling for language fallback in relative date formatter
    • #654 Fixed an issue when compiling library on Linux using round function (glib/darwin)
    • #658 Fixed httpFormat format which are not valid for Unicode Technical Reference #35
    Source code(tar.gz)
    Source code(zip)
  • 6.0.1(Mar 28, 2019)

  • 6.0.0(Mar 27, 2019)

    Released on: 2019-03-27

    Changes

    • #648 Swift 5 / Xcode 10.2 Compatibility
    • #642 Wrong toISO() output parsing date string from non Gregorian calendars
    • #643 Parsing ISO-8601 formatted week dates fails
    • #646 Relative date formatting never returns the "previous" value (now supports past/future/current)
    • #638 Added RoundingStrategy for RelativeFormatter.Gradation.Rule
    • #647 HTTP Header formatter fix
    Source code(tar.gz)
    Source code(zip)
  • 5.1.0(Jan 20, 2019)

    Released on: 2019-01-20

    Changelog

    • #622 Added enumeration methods to get dates for a specified weekday in a date range (see 3.12 section in documentation)
    • #634 Added Month and Year structures with circular operation support (ie. you can remove two days from monday and you got saturday or add two months to november to get january). All of these structures along with Weekday support localized display of the represented value.
    • #623 Fixed ambiguos operator error when subtracting a Date with TimeInterval
    • #626 Fixed ISO 8601 output when current calendar is not Gregorian
    • #627 Added Asia/Saigon in Zones enumeration
    • #631 Fixed RealtiveFormtter's toRelative() methods when no quantifier is available
    • #629 Fixed heuristic date guessing inside the formatter which prevents discovering wrong date
    • #628 Fixed ISO8601 output when printing date along with complete time
    • #619 Fixed a bug with isInRange where orEqual parameter is not passed correctly
    • #610 Refactoring to remove un-necessary self
    Source code(tar.gz)
    Source code(zip)
  • 5.0.13(Oct 28, 2018)

    Released on: 2018-10-28

    Changes

    • #555 Deprecated toString() of TimeInterval/Double to use toIntervalString() (in order to avoid ambiguity)
    • #611 Removed arc4random_uniform to use new Swift 4.2 random APIs
    • #568 Add Linux support to SwiftDate (see notices on documentation)
    Source code(tar.gz)
    Source code(zip)
  • 5.0.12(Oct 26, 2018)

    Released on: 2018-10-26

    Changes

    • #521 weekdayName(), eraName(), quarterName() allows to specify locale overwrite to region's locale
    • #596 Refactoring for hashValue in DateInRegion, fixed compiler error on watchOS target
    • #598 Silenced Xcode 'Conversion to Swift 4.2 is available' warning
    • #608 Fixed crash when using quarterName(.short) with a Date in 4th quarter of the year
    Source code(tar.gz)
    Source code(zip)
  • 5.0.11(Oct 26, 2018)

    Released on: 2018-10-26

    Changes

    • #597 Differences between two dates as DateComponents via componentsSince() method in DateInRegion
    • #602 Crash in RelativeFormatter when gradation was not found
    • #606 Added ms parameter to dateBySet() function to alter the milliseconds value of a date
    • #607 Fixed ambiguity for toDate(_:region:) with multiple formats bug
    • #609 isInRange ignores granularity parameter when used with plain Date
    Source code(tar.gz)
    Source code(zip)
  • 5.0.10(Oct 13, 2018)

  • 5.0.9(Sep 18, 2018)

    Released on: 2018-09-18 Swift: 4.x (4.0 and 4.2 supported)

    CHANGES

    FIXES

    • #592 Added .calendar and .locale property to configure ComponentsFormatterOptions struct to format TimeInterval values.
    • #588 Fixed some links in Documentation files
    • #585 Fixed .quarter property which return always a zero value
    • #586 Fixed ISO8601 parser crash with certain string configurations
    • #583 Fixed broken links in Manipulate_Date.md documentation file
    • #582 Fixed Decodable support for DateInRegion and compactMap() function.
    • #575 Fallback to language when language+region option for toRelative() function does not exists
    • #573 Fixed DateInRegion(milliseconds:) init to work with actual milliseconds values

    ADDITIONS

    • #574 Added customization via ComponentsFormatterOptions object in toString() of TimeInterval formatter (in addition to closure version of the same method)
    Source code(tar.gz)
    Source code(zip)
  • 5.0.7(Aug 24, 2018)

    Released on: 08/24/2018

    Changes

    • Added toUnit() to TimeInterval to extract single time component from an interval (as companion of toUnits()).
    • Removed calendar argument from toUnit() and toUnits(). Value is taken from reference's date region.calendar
    Source code(tar.gz)
    Source code(zip)
  • 5.0.6(Aug 21, 2018)

  • 5.0.5(Aug 3, 2018)

  • 5.0.4(Jul 18, 2018)

  • 5.0.3(Jul 13, 2018)

  • 5.0.2(Jul 12, 2018)

    Release Notes

    Release Date: 2018-07-12

    • #557 Fixed Swift Package Manager (SPM) project structure
    • #558 Added ordinalDay property to Date and DateInRegion (iOS 9+, macOS 10.11+)
    • Fixes for SwiftLint linter
    • Project converted to Swift 4.2
    Source code(tar.gz)
    Source code(zip)
  • 5.0.1(Jul 5, 2018)

  • 5.0.0(Jul 3, 2018)

    Upgrading from Swift 4.x

    SwiftDate 5.x is a complete rewrite of the library. While it introduces several new features a great part of the work is about a consistent naming of the functions: some was renamed while deprecated ones was removed.

    If you miss a features or you are interested in a new one create a new Issue.

    Important Note about Default Region

    In SwiftDate 4.x the default region is automatically set to local regiomn, where all attributes are set automatically to the current's device's locale, timezone and calendar.

    Since SwiftDate 5, in order to be more comply with Date's default behaviour, the default region's timezone is set to GMT+0 (UTC).

    If you want to restore the old behaviour just set it to Region.local just after the launch of the app.

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

    Added/Removed/Replaced Methods

    • Date.defaultRegion was renamed to SwiftDate.defaultRegion and you can both read and set it.
    • Date.setDefaultRegion(:) was removed; use SwiftDate.defaultRegion's setter.
    • TimeZoneName is now Zones and its conform to the new ZonesConvertible protocol. All parameters (like Region inits function) takes now a generic ZonesConvertible instance: this mean you can pass one of the enum values of the zone or just an instance of TimeZone object (or you can conform your own class to it).
    • CalendarName is now Calendars and its conform to the new CalendarConvertible protocol. All parameters (like Region inits function) takes now a generic CalendarConvertible instance: this mean you can pass one of the enum values of the zone or just an instance of Calendar object (or you can conform your own class to it).
    • LocaleName is now Locales and its conform to the new LocaleConvertible protocol. All parameters (like Region inits function) takes now a generic LocaleConvertible instance: this mean you can pass one of the enum values of the zone or just an instance of Calendar object (or you can conform your own class to it).
    • Date/DateInRegion: isBetween() function was renamed isInRange()
    • Date/DateInRegion: isAfter() was renamed to isAfterDate()
    • Date/DateInRegion: isBefore() was renamed to isBeforeDate()
    • String extension methods date(format:fromRegion) and date(formats:fromRegion) are now replaced by toDate(_:region) (while similar shortcuts methods are added to parse common formats: toISODate(), toDotNETDate(), toRSSDate() and toSQLDate().
    • Removed Int extension second,minute,hour,day,week,month,year due to inconsistence (use plurar versions seconds,minutes etc.
    • Related dates generation is now grouped under the dateAt() function as enum list. Therefore nextWeekend, `previo
    • DateInRegion: roundedAt() is now replaced by dateRoundedAt() which now compacts paramters in a single enum.
    • DateInRegion: startOf() and endOf() are now replaced by dateAtStartOf() and dateAtEndOf()and include support for both single and multiple units.
    • DateInRegion: atTime() is now replaced by dateBySet(hour:min:secs:options)
    • DateInRegion: DateInRegion's static distantFuture() and distantPast are now future() and past()
    • DateInRegion:next(day:) is now part of the dateAt() function with enum .weekday(_).
    • DateInRegion: add(components:) is now replaced by dateByAdding(_:_:)
    • DateInRegion: at(unit:value:) and at(values:keep:) are now replaced by dateBySet().
    • nextDSTTransitionDate property is now part of the enum of dateAt()
    • recentDate() and oldestDate() are now called newestIn() and oldestIn()
    • TimeInterval Extension: in(_:toDate:of:) is now replaced by toUnits(_:from:)
    • TimeInterval Extension: string() is now replaced by toString()
    • DateTimeInterval class is now replaced by TimePeriod class and its descendants
    • DateInRegion: dates(between:and:increment:) to enumerate dates is now replaced by enumerateDates(from:to:increment:)
    • DateInRegion: colloquial formatter colloquial(toDate:options:) is now replaced by toRelative(since:style:locale:)
    • Formatting method iso8601() is now toISO8601() and other methods to..() was added to simplify formatting task.
    • Date/DateInRegion: Introduced compareCloseTo() to compare two dates against a precision value.
    • Added several shortcut methods as extensions of String to parse dates: toISODate(), toDotNETDate(), toRSSDate() and toSQLDate().
    • Comparison methods are now grouped by compare() function and a list of all available enums.
    Source code(tar.gz)
    Source code(zip)
  • 4.5.0(Nov 26, 2017)

    CHANGELOG

    • #495 Added Thai language (thanks to Thanakrit Weekhamchai)
    • #492 Introduced a new ColloquialDateFormatter class
    • #503 Added isBetween to check if a date is inside a given dates range with passed granularity.
    • #505 Exposed reference date for in() function of TimeInterval. If specified conversion of the interval is aware of daylight saving time and calendar's specific dates; when not specified absolute conversion still available (only for .day,.hour,.minute,.second components).
    Source code(tar.gz)
    Source code(zip)
  • 4.4.2(Oct 26, 2017)

  • 4.4.1(Sep 15, 2017)

  • 4.4.0(Sep 14, 2017)

  • 4.3.0(Sep 14, 2017)

  • 4.1.11(Sep 5, 2017)

  • 4.1.10(Sep 3, 2017)

    Changelog:

    • #472 CalendarName now supports RawRepresentable protocol
    • #459 Fixed an issue with translation of Dutch locale
    • #463 colloquial...() functions now fallback to timeComponents... functions when style is set to an abbreviated form (ie to return 1h)
    • #464 Fixed unit tests for ISO8501
    • #461 Fixed translation for Slovak locale
    • #470 Added Azerbaijani Latin locale (thanks to @elshad)
    • #468 Fixed an issue with negative intervals in DateTimeInterval (regression from previous release)
    Source code(tar.gz)
    Source code(zip)
Owner
Daniele Margutti
iOS & macOS Engineer, UI/UX Lover. Continuous improvement is better than delayed perfection.
Daniele Margutti
Dates and times made easy in iOS

DateTools DateTools was written to streamline date and time handling in iOS. Classes and concepts from other languages served as an inspiration for Da

Matthew York 7.2k Dec 30, 2022
DateHelper - A high performant Swift Date Extension for creating, converting, comparing, or modifying dates.

DateHelper A high performant Swift Date Extension for creating, converting, comparing, or modifying dates. Capabilities Creating a Date from a String

Melvin Rivera 1.4k Jan 2, 2023
Punctual - Swift dates, more fun. Heavily inspired by ObjectiveSugar

Punctual Swift dates, more fun. Heavily inspired by ObjectiveSugar Installation Punctual is available through the Swift Package Manager! Just add this

Harlan Haskins 321 Jun 30, 2022
ЁЯХР Format your dates/times as emojis.

EmojiTimeFormatter Format your dates/times as emojis ?? ?? ?? Description You can build easy to understand user interfaces with EmojiTimeFormatter or

Thomas Paul Mann 80 Feb 7, 2022
SwiftUI library to display a clock. You can move the arms to change the time, change the style of the clock and customise some configurations.

SwiftClockUI Clock UI for SwiftUI This library has been tested тЬЕ ?? macOS Catalina 10.15.3 тЬЕ ?? macOS Big Sur 11.6 тЬЕ ?? iOS 13 тЬЕ ?? iOS 14 тЬЕ ?? iOS 15

Renaud Jenny 239 Dec 29, 2022
A "time ago", "time since", "relative date", or "fuzzy date" category for NSDate and iOS, Objective-C, Cocoa Touch, iPhone, iPad

Migration 2014.04.12 NSDate+TimeAgo has merged with DateTools. DateTools is the parent project and Matthew York is the project head. This project is n

Kevin Lawler 1.8k Dec 2, 2022
A TimeZonePicker UIViewController similar to the iOS Settings app. Search and select from a range of cities and countries to find your most suitable time zone.

TimeZonePicker A TimeZonePicker UIViewController similar to the iOS Settings app. Search and select from a range of cities and countries to find your

Gligor Kotushevski 125 Dec 13, 2022
A basic countdown app that allows the user to create, edit, and delete events. Each event contains a live countdown timer to a specified date and time.

Event Countdown App (iOS) Created by Lucas Ausberger About This Project Created: January 4, 2021 Last Updated: January 8, 2021 Current Verison: 1.1.1

Lucas Ausberger 1 Jan 8, 2022
Time is a Swift package that makes dealing with calendar values a natural and straight-forward process.

Time Time is a Swift package that makes dealing with calendar values a natural and straight-forward process. Working with calendars can be extremely c

Dave DeLong 2k Dec 31, 2022
SwiftMoment - A time and calendar manipulation library for iOS 9+, macOS 10.11+, tvOS 9+, watchOS 2+ written in Swift 4.

SwiftMoment This framework is inspired by Moment.js. Its objectives are the following: Simplify the manipulation and readability of date and interval

Adrian Kosmaczewski 1.6k Dec 31, 2022
NTP library for Swift and Objective-C. Get the true time impervious to device clock changes.

TrueTime for Swift Make sure to check out our counterpart too: TrueTime, an NTP library for Android. NTP client for Swift. Calculate the time "now" im

Instacart 530 Jan 4, 2023
Custom Time Picker ViewController with Selection of start and end times in Swift ЁЯФ╢

LFTimePicker Custom Time Picker ViewController with Selection of start and end times in Swift ?? . Based on Adey Salyard's design @ Dribbble One to tw

Awesome Labs 65 Nov 11, 2022
Timekeeper is an easy-to-use time measurement library written in Swift, with support for iOS, tvOS, watchOS and macOS.

Timekeeper is an easy-to-use time measurement library written in Swift, with support for iOS, tvOS, watchOS and macOS. Installation Timekee

Andreas Pfurtscheller 1 Oct 18, 2021
Date and time manager for iOS/OSX written in Swift

Tempo was designed to work both in OSX and in iOS (7.0+). Work with the time or dates can be cumbersome, iOS development. Tempo allows you to deal easly with date and time. Basics manipulations are already implemented in Tempo.

Remi ROBERT 153 Jun 3, 2021
NVDate is an extension of NSDate class (Swift4), created to make date and time manipulation easier.

NVDate is an extension of NSDate class (Swift4), created to make date and time manipulation easier. NVDate is testable and robust, we wrote intensive test to make sure everything is safe.

Noval Agung Prayogo 177 Oct 5, 2022
Time Lines - Know when all your friends, colleagues, and family are

Time Lines Know when all your friends, colleagues, and family are. Time Lines is a practical app to know when all your friends, colleagues and family

Mathieu Dutour 50 Dec 14, 2022
ЁЯХ░ Type-safe time calculations in Swift

Time This micro-library is made for you if: You have ever written something like this: let interval: TimeInterval = 10 * 60 To represent 10 minutes. U

Oleg Dreyman 1.1k Dec 21, 2022
Building a better date/time library for Swift

Time Time is a Swift package that makes dealing with calendar values a natural and straight-forward process. Working with calendars can be extremely c

Dave DeLong 2k Dec 31, 2022
Swifty Date & Time API inspired from Java 8 DateTime API.

AnyDate Swifty Date & Time API inspired from Java 8 DateTime API. Background I think that date & time API should be easy and accurate. Previous dates,

Jungwon An 182 Dec 1, 2022