NSDate Tutorial – create a NSDate from a String or from NSDateComponents

This will be a very short and simple tutorial on working with an NSDate. In reality this is a precursor to the next tutorial which is on Local Notifications, but a notification takes an NSDate so I figured I would throw this together first and it will help clear up a loose end for myself and my documentation. In addition it will serve a purpose for anyone searching for a simple way to create a date but not interested in the Local Notifications tutorial.

Simulator Shot

I am going to demonstrate a couple different ways to create an NSDate Object. The first method will create a NSString from the current date and time. We will then use that string to create an NSDate object from the NSString. Finally we will parse the string into individual elements and create the NSDate object from NSDateComponents.

So let’s get started.

1.) First create a View-based Application named DateTutorial.

2.) Open up DateTutorialViewController.h and add IBOutlet for seven UILabels. We’re also going to add an IBAction that gets today’s date when we press a button, and another IBAction that will parse the date into separate components. We also need to declare a NSString that will hold our date as a string.

Header File

3.) Then open up the implementation file (DateTutorialViewController.m) and synthesize the variables we just added to the header file.

synthesize variables

4.) Open the nib file by double clicking on DateTutorialViewController.xib in the Resources folder. We’re going to add six UILabels to the view and two UIButtons. The first UILabel will display today’s date when we press the first button, which will call the IBAction getTodaysDate. The second button will parse the date string we have into individual NSDateComponents. And display them in the other five UILabels.

IB View

Connect that it all up in the Connections Inspector. Each label gets connected to appropriate IBOutlet Label and the buttons get connected to the appropriate IBActions.

Connections Inspector

5.) That’s it in Interface Builder for now so save and close and go back to Xcode. Open up DateTutorialViewController.m and let’s implement the getTodaysDate method first.

The first thing we do is create a NSDateFormatter that we will use for our date. We set format we want the date to be displayed as. We set our time zone. I am in the USA in Central Standards Time which is 18000 seconds, or 5 hours, earlier than GMT. After we have our formatter set up we get today’s date and stick it in the NSString we created to hold it and then set that string into our date label on the user interface.

getTodaysDate method

You click Build and Run now if you want to see the date.

Simulator Shot

6.) Let’s add one more thing to that method. Let’s create a date object from our string and print it out the console.

We’re going to use the same formatter we already created but since we’ve already got the correct time we need to set the time zone back to GMT other wise it will want to subtract 5 more hours from the time we already have.

add to getTodaysDate method

Okay now run it again and you’ll see our new date printed out to the console.


7.) The last thing we’ll do is implement our parseDate method to create NSDateComponents to populate the rest of our labels. Then we’ll create a date from those components.

We create a NSString and get the subString we need for each piece of the date. Then we use those NSStrings to create NSDateComponents. And finally we put those components together using NSCalendar to create a NSDate.

parseDate method

That’s pretty much it. A lot of extra stuff just to demonstrate getting a date, but it makes it more fun that way I think.

Build and Run and see it in action.

Final App

Here’s the code.

This entry was posted in Uncategorized and tagged , , , , , , , , , , . Bookmark the permalink.

5 Responses to NSDate Tutorial – create a NSDate from a String or from NSDateComponents

  1. Anonymous says:

    Perfect Thanks. Very helpful.

  2. Rick says:

    Thanks for a great tutorial! I have been searching for something like this for the past few weeks…..

    Any chance of a tip…. when parsing the date how could you add a set number of days – for example you click parse date and the date displayed is 21 days from todays date.

    Thanks again,


    • Kent says:

      Check out the NSCalendar and it’s methods.

      Good Luck

      • Rick says:

        Dear Kent,

        Thanks for the tip – I thought this would work, but I just keep getting undeclared identifier errors for dateByAddingComponents – this is declared in NSCalendar.h – which is already referenced in my project….. very frustrating!


        NSDateComponents *comps = [[NSDateComponents alloc] init];
        [comps setDay:3];
        NSDate *date1 = [dateByAddingComponents:comps toDate:currentDate options:0];

        NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];


  3. Dario says:

    Hello, thanks for posting this, it has been very helpful and is clearer than the Apple Documentation on the issue.

    I do have one query though…

    If you don’t set the NSTimeZone for the formatter, it will default to the system/phone’s default correct? If that’s the case is choosing to implement the change to and from GMT a ‘just in case’?

    I’m just thinking in getTodaysDate the line:
    todaysDate = [formatter stringFromDate:[NSDate date]];
    Would bring you back a -18000 seconds version of the date anyway wouldn’t it, with the preceding line about setting the time zone?
    Although calling the description method of the object will give you a +0000 value of the time, if you’re calling it from the formatter the returned string would be -18000 without needing to specify the time zone.

    The same is true when you recreate the date. Although you’re creating it from the string the offset is not being acted on until you get a string from that date using the formatter which will again set it to the correct time.

    I was just trying to work out if setting the time zones manually was to overcome a possible lack of default setting? Or if there was some other reason I was missing.

    Thanks again for the tutorial, it’s very good and as I said, much clearer than the Apple Docs :)

Add Comment Register

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>