Advertise here

Advertise here

Howdy, Stranger!

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

Using NSCalendar, NSDateComponents, to get current time as integer hours/minutes/seconds

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

ClockAnimation demo on github

I needed the current time as integer hours, minutes, and seconds.

I've used NSCalendar enough that I found it easy, but it was harder the first time I needed to do this, so I thought I'd write a short tutorial on it.

I set up my class to have an instance variable that holds an NSCalendar object. I create it lazily (only initialize it if it is nil, and only when I need it the first time)

In my case, I use the user's current locale, so it will use the current time zone:
//Lazily create a calenadar object;
  if (!calendar)   //NSGregorianCalendar
    calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];

Then I just ask the calendar to give me the hours, minutes, and seconds as NSDateComponents:
//Ask our calendar for the current hour/minute/second
  NSDateComponents *timeComponents = [calendar components: 
    NSHourCalendarUnit + NSMinuteCalendarUnit + NSSecondCalendarUnit 
    fromDate: date];
  NSInteger hour = timeComponents.hour %12;
  NSInteger minute = timeComponents.minute;
  NSInteger second = timeComponents.second;

I was too lazy to worry about whether the hours was in 12 or 24 hour format, so I just took the result modulo 12.

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.