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

Matthew Campbell, March 10th, 2009

iStock_000007860540XSmall.jpg

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:

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?

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