DateTools was written to streamline date and time handling in iOS. Classes and concepts from other languages served as an inspiration for DateTools, especially the DateTime structure and Time Period Library for .NET. Through these classes and others, DateTools removes the boilerplate required to access date components, handles more nuanced date comparisons, and serves as the foundation for entirely new concepts like Time Periods and their collections.
All the classes required for DateTools are located in the DateTools folder in the root of this repository. They are listed below:
Swift (Found in DateToolsSwift/DateTools)
Objective-C (Found in DateTools/DateTools)
The following bundle is necessary if you would like to support internationalization or would like to use the "Time Ago" functionality. You can add localizations at the
Localizations subheading under
Info in the
DateTools.h contains the headers for all the other files. Import this if you want to link to the entire framework.
Table of Contents
- Time Periods
- Time Period Groups
- Unit Tests
Full code documentation can be found here
One of the missions of DateTools was to make Date feel more complete. There are many other languages that allow direct access to information about dates from their date classes, but Date (sadly) does not. It safely works only in the Unix time offsets through the
timeIntervalSince... methods for building dates and remains calendar agnostic. But that's not always what we want to do. Sometimes, we want to work with dates based on their date components (like year, month, day, etc) at a more abstract level. This is where DateTools comes in.
No date library would be complete without the ability to quickly make an NSString based on how much earlier a date is than now. DateTools has you covered. These "time ago" strings come in a long and short form, with the latter closely resembling Twitter. You can get these strings like so:
let timeAgoDate = 2.days.earlier print("Time Ago: ", timeAgoDate.timeAgoSinceNow) print("Time Ago: ", timeAgoDate.shortTimeAgoSinceNow) //Output: //Time Ago: 2 days ago //Time Ago: 2d
Assuming you have added the localization to your project,
DateTools currently supports the following languages:
- ar (Arabic)
- bg (Bulgarian)
- ca (Catalan)
- zh_Hans (Chinese Simplified)
- zh_Hant (Chinese Traditional)
- cs (Czech)
- da (Danish)
- nl (Dutch)
- en (English)
- fi (Finnish)
- fr (French)
- de (German)
- gre (Greek)
- gu (Gujarati)
- he (Hebrew)
- hi (Hindi)
- hu (Hungarian)
- is (Icelandic)
- id (Indonesian)
- it (Italian)
- ja (Japanese)
- ko (Korean)
- lv (Latvian)
- ms (Malay)
- nb (Norwegian)
- pl (Polish)
- pt (Portuguese)
- ro (Romanian)
- ru (Russian)
- sl (Slovenian)
- es (Spanish)
- sv (Swedish)
- th (Thai)
- tr (Turkish)
- uk (Ukrainian)
- vi (Vietnamese)
- cy (Welsh)
- hr (Croatian)
If you know a language not listed here, please consider submitting a translation. Localization codes by language.
This project is user driven (by people like you). Pull requests close faster than issues (merged or rejected).
Thanks to Kevin Lawler for his work on NSDate+TimeAgo, which has been officially merged into this library.
There is a lot of boilerplate associated with getting date components from an Date. You have to set up a calendar, use the desired flags for the components you want, and finally extract them out of the calendar.
With DateTools, this:
//Create calendar let calendar = Calendar(identifier: .gregorian) let dateComponents = calendar.dateComponents(Set<Calendar.Component>([.month,.year]), from: Date()) //Get components let year = dateComponents.year! let month = dateComponents.month!
let year = Date().year let month = Date().month
The date editing methods in DateTools makes it easy to shift a date earlier or later by adding and subtracting date components. For instance, if you would like a date that is 1 year later from a given date, simply call the method
With DateTools, this:
//Create calendar NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:[NSDate defaultCalendar]]; NSDateComponents *components = [[NSDateComponents alloc] init]; //Make changes [components setYear:1]; //Get new date with updated year NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];
NSDate *newDate = [date dateByAddingYears:1];
Subtraction of date components is also fully supported through the
Another mission of the DateTools category is to greatly increase the flexibility of date comparisons. Date gives you four basic methods:
laterDate: are great, but it would be nice to have a boolean response to help when building logic in code; to easily ask "is this date earlier than that one?". DateTools has a set of proxy methods that do just that as well as a few other methods for extended flexibility. The new methods are:
These methods are great for comparing dates in a boolean fashion, but what if we want to compare the dates and return some meaningful information about how far they are apart? Date comes with two methods
timeIntervalSinceNow which gives you a
double offset representing the number of seconds between the two dates. This is great and all, but there are times when one wants to know how many years or days are between two dates. For this, DateTools goes back to the ever-trusty NSCalendar and abstracts out all the necessary code for you.
With Date Tools, this:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:[NSDate defaultCalendar]]; NSDate *earliest = [firstDate earlierDate:secondDate]; NSDate *latest = (secondDate == firstDate) ? secondDate : firstDate; NSInteger multiplier = (secondDate == firstDate) ? -1 : 1; NSDateComponents *components = [calendar components:allCalendarUnitFlags fromDate:earliest toDate:latest options:0]; NSInteger yearsApart = multiplier*(components.month + 12*components.year);
NSInteger yearsApart = [firstDate yearsFrom:secondDate];
Methods for comparison in this category include:
Formatted Date Strings
Just for kicks, DateTools has a few convenience methods for quickly creating strings from dates. Those two methods are
formattedDateWithFormat:. The current locale is used unless otherwise specified by additional method parameters. Again, just for kicks, really.
Dates are important, but the real world is a little less discrete than that. Life is made up of spans of time, like an afternoon appointment or a weeklong vacation. In DateTools, time periods are represented by the TimePeriod class and come with a suite of initializaiton, manipulation, and comparison methods to make working with them a breeze.
Time peroids consist of an Date start date and end date. To initialize a time period, call the init function.
DTTimePeriod *timePeriod = [[DTTimePeriod alloc] initWithStartDate:startDate endDate:endDate];
or, if you would like to create a time period of a known length that starts or ends at a certain time, try out a few other init methods. The method below, for example, creates a time period starting at the current time that is exactly 5 hours long.
DTTimePeriod *timePeriod = [DTTimePeriod timePeriodWithSize:DTTimePeriodSizeHour amount:5 startingAt:[NSDate date]];
Time Period Info
A host of methods have been extended to give information about an instance of TimePeriod. A few are listed below
hasStartDate- Returns true if the period has a start date
hasEndDate- Returns true if the period has an end date
isMoment- Returns true if the period has the same start and end date
durationIn....- Returns the length of the time period in the requested units
Time periods may also be manipulated. They may be shifted earlier or later as well as expanded and contracted.
When a time period is shifted, the start dates and end dates are both moved earlier or later by the amounts requested.
To shift a time period earlier, call
shiftEarlierWithSize:amount: and to shift it later, call
shiftLaterWithSize:amount:. The amount field serves as a multipler, just like in the above initializaion method.
When a time periods is lengthened or shortened, it does so anchoring one date of the time period and then changing the other one. There is also an option to anchor the centerpoint of the time period, changing both the start and end dates.
An example of lengthening a time period is shown below:
DTTimePeriod *timePeriod = [DTTimePeriod timePeriodWithSize:DTTimePeriodSizeMinute endingAt:[NSDate date]]; [timePeriod lengthenWithAnchorDate:DTTimePeriodAnchorEnd size:DTTimePeriodSizeMinute amount:1];
This doubles a time period of duration 1 minute to duration 2 minutes. The end date of "now" is retained and only the start date is shifted 1 minute earlier.
There may come a need, say when you are making a scheduling app, when it might be good to know how two time periods relate to one another. Are they the same? Is one inside of another? All these questions may be asked using the relationship methods of TimePeriod.
Below is a chart of all the possible relationships between two time periods:
A suite of methods have been extended to check for the basic relationships. They are listed below:
You can also check for the official relationship (like those shown in the chart) with the following method:
All of the possible relationships have been enumerated in the TimePeriodRelation enum.
For a better grasp on how time periods relate to one another, check out the "Time Periods" tab in the example application. Here you can slide a few time periods around and watch their relationships change.
Time Period Groups
Time period groups are the final abstraction of date and time in DateTools. Here, time periods are gathered and organized into something useful. There are two main types of time period groups,
TimePeriodChain. At a high level, think about a collection as a loose group where overlaps may occur and a chain a more linear, tight group where overlaps are not allowed.
Both collections and chains operate like an NSArray. You may add,insert and remove TimePeriod objects from them just as you would objects in an array. The difference is how these periods are handled under the hood.
Time Period Collections
Time period collections serve as loose sets of time periods. They are unorganized unless you decide to sort them, and have their own characteristics like a StartDate and EndDate that are extrapolated from the time periods within. Time period collections allow overlaps within their set of time periods.
To make a new collection, call the class method like so:
//Create collection DTTimePeriodCollection *collection = [DTTimePeriodCollection collection]; //Create a few time periods DTTimePeriod *firstPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2014 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]]; DTTimePeriod *secondPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2016 11 05 18:15:12.000"]]; //Add time periods to the colleciton [collection addTimePeriod:firstPeriod]; [collection addTimePeriod:secondPeriod]; //Retreive collection items DTTimePeriod *firstPeriod = collection;
Sorting time periods in a collection is easy, just call one of the sort methods. There are a total of three sort options, listed below:
- Start Date -
- End Date -
- Time Period Duration -
It is also possible to check an Date's or TimePeriod's relationship to the collection. For instance, if you would like to see all the time periods that intersect with a certain date, you can call the
Time Period Chains
Time period chains serve as a tightly coupled set of time periods. They are always organized by start and end date, and have their own characteristics like a StartDate and EndDate that are extrapolated from the time periods within. Time period chains do not allow overlaps within their set of time periods. This type of group is ideal for modeling schedules like sequential meetings or appointments.
To make a new chain, call the class method like so:
//Create chain DTTimePeriodChain *chain = [DTTimePeriodChain chain]; //Create a few time periods DTTimePeriod *firstPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2014 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"]]; DTTimePeriod *secondPeriod = [DTTimePeriod timePeriodWithStartDate:[dateFormatter dateFromString:@"2015 11 05 18:15:12.000"] endDate:[dateFormatter dateFromString:@"2016 11 05 18:15:12.000"]]; //Add test periods [chain addTimePeriod:firstPeriod]; [chain addTimePeriod:secondPeriod]; //Retreive chain items DTTimePeriod *firstPeriod = chain;
Any time a date is added to the time chain, it retains its duration, but is modified to have its StartDate be the same as the latest period in the chain's EndDate. This helps keep the tightly coupled structure of the chain's time periods. Inserts (besides those at index 0) shift dates after insertion index by the duration of the new time period while leaving those at indexes before untouched. Insertions at index 0 shift the start date of the collection by the duration of the new time period. A full list of operations can be seen below.
Like collections, chains have an equality check and the ability to be shifted earlier and later. Here is a short list of other operations.
All methods and variables have been documented and are available for option+click inspection, just like the SDK classes. This includes an explanation of the methods as well as what their input and output parameters are for. Please raise an issue if you ever feel documentation is confusing or misleading and we will get it fixed up!
Unit tests were performed on all the major classes in the library for quality assurance. You can find theses under the "Tests" folder at the top of the library. There are over 300 test cases in all!
If you ever find a test case that is incomplete, please open an issue so we can get it fixed.