getting current hour, minutes and seconds in iPhone

How can I get the current hour, minutes, and seconds from this?

NSDate *now = [NSDate date];

Thanks! I want to have 3 int variables with the values stored in them, not a string which displays the values.

Answers


You need to use NSDateComponents, which is a bit tricky (not to mention verbose!) since you need to understand a bit about the way Cocoa handles calendars. There's a great intro in the docs; here's a modified excerpt:

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components =
                    [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today];

NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];

NSDateFormatter * formatter;

self.formatter = [[NSDateFormatter alloc] init];

[_formatter setDateFormat:@"HH:mm:ss"];

NSDate *today = [NSDate date];

NSString *p_time = [_formatter stringFromDate:today];

Need Your Help

response time of the PCI-6602 Counter/Timer module

hardware labview

I am using a NI PCI-6602 Counter/Timer to send TTL signals to another device in our lab. I have to send the signal every ~ 3 - 5 ms, but this time is not fixed (it depends on some other processes I...

Android update widget ListView

android service android-listview refresh

I'm working on a app with a widget which I want to update on a regular basis. I've set android:updatePeriodMillis="3600000" but my ListView doesn't update. What is it that I'm missing?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.