Here’s a Quick Way to Deal with Dates in Objective-C

Matthew Campbell, March 10th, 2009

If you have been pulling your hair out all day looking for a straightforward way to deal with dates in your iPhone project, then this post is for you.

NSDate is the name of the class that is used to work with dates and NSDateFormatter is used to transform dates into something that can be presented to the user.

The most common thing people want to do with dates is to simply get today’s date. Here is how you do that:

NSDate *date =[NSDate date];

Now, if you were to write this out to the log or use as text on a user control then you would end up with something like this:

2009-03-10 08:36:33 -0400

It is sensible, but probably not what you are looking for. To pretty this up, use NSDateFormatter like so:


NSDateFormatter *df = [[NSDateFormatter alloc] init];

df.dateStyle = NSDateFormatterLongStyle;

[ASFunctions 
    logThis:@"formatted date:" 
    andThisObject:[df stringFromDate:date]];

[df release];

This code will output something like this to the log:

March 10, 2009

Nicer, huh? This is more likely the type of thing that you will want your users to see.

A few notes about this:

  • If you use NSDateFormatter then you must alloc and then release the object.
  • NSDate does not require this because NSDate has helper functions that return autoreleased objects.
  • Set the “dateStyle” property of the NSDate object that you create for different display options.
  • ASFunctions is my pet class I use to help automate some tasks (see my previous blog post about this)

But How Do You Get the Date When It Is Not Today’s Date?

This is actually pretty easy. All you need to do is this:


NSDate *date = [NSDate 
    dateWithNaturalLanguageString:@"07/17/07"];

This should get you started – does anyone else have any tips on working with dates on the iPhone?

Comments

This is great for dates, but how about displaying time along with the date?

Moebius, March 27th, 2009