Skip to content

Instantly share code, notes, and snippets.

@joemasilotti
Last active February 25, 2016 22:16
Show Gist options
  • Save joemasilotti/8d80db6b4f453894bbac to your computer and use it in GitHub Desktop.
Save joemasilotti/8d80db6b4f453894bbac to your computer and use it in GitHub Desktop.
NSDate Manipulation in iOS 8

This gist accompanies the blog post NSDate Manipulation Made Easy in iOS 8.

Apple quietly introduced a whole new suite of public API methods to NSCalendar in iOS 8 titled “Calendrical Calculations”. For some reason they seemed to have forgotten to include them in the public documentation on their developer site. Fortunately, digging in to the header file in Xcode reveals lots of descriptive comments about how to use these powerful new ways of interacting with NSDate objects.

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDate *laterToday = [calendar dateByAddingUnit:NSCalendarUnitMinute
value:20
toDate:today
options:kNilOptions];
NSComparisonResult result1 = [calendar compareDate:today
toDate:laterToday
toUnitGranularity:NSCalendarUnitDay];
// result1 = NSOrderedSame
NSDate *tomorrow = [calendar dateByAddingUnit:NSCalendarUnitHour
value:24
toDate:today
options:kNilOptions];
NSComparisonResult result2 = [calendar compareDate:today
toDate:tomorrow
toUnitGranularity:NSCalendarUnitDay];
// result2 = NSOrderedAscending
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
[calendar isDateInToday:today];
[calendar isDateInTomorrow:today];
[calendar isDateInYesterday:today];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *nextNineThirty = [calendar nextDateAfterDate:[NSDate date]
matchingHour:9
minute:30
second:0
options:kNilOptions];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *threeHoursFromNow = [calendar dateByAddingUnit:NSCalendarUnitHour
value:3
toDate:[NSDate date]
options:NSCalendarMatchNextTime];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment