iOS - Objective-C - Working with NSDate

Stephen Zaharuk / Tuesday, April 15, 2014

If you're not familiar with objective-c, NSDate is the equivalent of the DateTime object in C#. However working with it is quite different. In this article i'll show you how to do some common tasks with the NSDate object. 

Get Today's Date:

NSDate* date = [NSDate date];

Create a Date From Scratch:

NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.year = 2014;
comps.month = 3;
comps.day = 31;

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDate* date = [calendar dateFromComponents:comps];

Add a day to a Date:

NSDate* date = [NSDate date];

NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = 1;

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDate* tomorrow = [calendar dateByAddingComponents:comps toDate:date options:nil];

Subtract a day from a Date:

NSDate* date = [NSDate date];

NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.day = -1;

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDate* yesterday = [calendar dateByAddingComponents:comps toDate:date options:nil];

Convert a Date to a String:

NSDate* date = [NSDate date];

NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSString* dateString = [formatter stringFromDate:date];

Convert a String to a Date:

NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = @"MMMM dd, yyyy";
NSDate* date = [formatter dateFromString:@"August 02, 2014"];

Find how many days are in a month:

NSDate* date = [NSDate date];

NSCalendar* cal = [NSCalendar currentCalendar];
NSRange currentRange = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
NSInteger numberOfDays = currentRange.length;

Calculate how much time something took:

NSDate* start = [NSDate date];

for(int i = 0; i < 1000000000; i++);

NSDate* end = [NSDate date];
NSTimeInterval duration = [end timeIntervalSinceDate:start];

Find the Day Of Week for a specific Date:

NSDate* date = [NSDate date];
NSCalendar* cal = [NSCalendar currentCalendar];
NSInteger dow = [cal ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:date];

Enjoy!

By Stephen Zaharuk (SteveZ)