NSDate Helper - Making Cocoa's NSDate A Little Less Painful

This is a category for the NSDate class that provides some convenience methods for working with NSDate objects and displaying formatted and relative strings. It's available for free on Github, anyone is welcome to fork and send pull requests, it's always appreciated.

More information can be found at my initial blog post .

NSDate (Helper) on Github


Two convenience methods make it easy for you to display some relative date information. stringForDisplayFromDategives you the kind of relative you see in the Notes listing on the iPhone:

NSString *displayString = [NSDate stringForDisplayFromDate:date];

This produces the following kinds of output:

  • ‘3:42 AM’ – if the date is after midnight today
  • ‘Tuesday’ – if the date is within the last seven days
  • ‘Mar 1’ – if the date is within the current calendar year
  • ‘Mar 1, 2008’ – else ;-)

Another set of methods provide days-ago information:

  NSDate *date = [NSDate date];
  [date daysAgo]; // provides an NSComponent-based NSUInteger describing days ago.
  [date daysAgoAgainstMidnight]; // better version of daysAgo, works off midnight.
  [date stringDaysAgo]; // 'Today', 'Yesterday', or 'N days ago'.

Tired of creating and releasing date formatters? Missing things like to_s(:db)? Me, too. NSDate (Helper) has some static methods to make going back and forth between strings and dates a little less painful, and particularly easier when working with database timestamps (a la SQLite):

  NSDate *date = [NSDate dateFromString:@"2009-03-01 12:15:23"]; 
  NSString *dbDateString = [NSDate stringFromDate:date]; // returns '2009-03-01 12:15:23'

Who needs NSDateFormatter?

NSString *otherDateString = [NSDate stringFromDate:date withFormat:@"EEEE"]; // use any format you like


To use it in your Cocoa project, import the header and implementation files, and then add the header to your project’s_prefix.pch file so that it’s available across your project:

#ifdef __OBJC__
    #import <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    #import "NSDate+Helper.h"