Advertise here

Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Generating a time string/converting a time string to an NSDate using NSDateFormatter

Duncan CDuncan C Posts: 9,112Tutorial Authors, Registered Users @ @ @ @ @ @ @
In the clock app I just posted to github:

ClockAnimation demo on github

I needed to display the current time as a string "hh:mm:ss". I also wanted to be able to set the clock hands to an arbitrary value, and since I created a date formatter, I decided to use it to take a time string and convert it to an NSDate.

I make my time NSDateFormatter an instance variable and load it lazily so I'm not creating a new one every second:
if (!timeFormatter)
    timeFormatter = [[NSDateFormatter alloc] init];
    timeFormatter.dateFormat = @h:mm:ss;

Then it's a simple matter to get a string from an NSDate:
NSString *timeString = [timeFormatter stringFromDate: date];
and install it into a label:
timeTextLabel.text = timeString;

And for testing I wanted to be able to set the clock hands to a specific time, so I wrote this method:
- (void) setTimeWithTimeString: (NSString *) timeString;
  NSDate *date = [timeFormatter dateFromString: timeString];
  [self setTimeToDate: date animated: NO];

This code creates a date TODAY with the specified time. I didn't care about that. I just wanted an NSDate with the correct time value.
Duncan C

Animated GIF created with Face Dancer, available for free in the app store.

I'm available for one-on-one help at CodeMentor
Sign In or Register to comment.