May 21st, 2013 by miketsprague

NSDate is a pain, try NiceDate

NSDate sucks to work with and if you've ever used it, I'm sure you'll agree.

In order to modify a date object, you need to create a calendar (make sure it's gregorian!), create date components with a current NSDate, modify the date components, then grab the NSDate from them.

It's not particularly difficult, but it is annoying having to dig through code each time I want to change around a date.

For example, if we want to create a function that increments an NSDate by one month, we have to do the following:

-(NSDate*)oldIncrementMonth:(NSDate*)date
{
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [gregorian components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:date];
    [dateComponents setMonth:[dateComponents month]+1];
    return [gregorian dateFromComponents:dateComponents];
}

That's not really readable... and personally, I find it revolting.

So I made an easy to use alternative called NiceDate.
Check out that same example:

-(NSDate*)incrementMonth:(NSDate*)date
{
    NiceDate *niceDate = [NiceDate niceDateWithDate:date];
    niceDate.month++;
    return niceDate.date;
}

A little cleaner, don't you think?

I also added formatting functionality so you don't have to touch a date formatter:

niceDate.format = @"MM-dd-YYYY";

From here, you can do whatever you wish with it.

NSString *prettyDate = [NSString stringWithFormat:@"%@", niceDate];

Check it out over on GitHub and let me know what you think!

Read more from miketsprague