26

Whats the best way to get the current time (HH:MM:SS) using Objective-C. I would guess I should be looking at NSDate & NSDateFormatter. I had a quick glance at the docs and it looked a little more convoluted than I expected, so I thought I would check here to make sure I was on the right track.

gary

fuzzygoat
  • 26,573
  • 48
  • 165
  • 294

3 Answers3

64
NSDate * now = [NSDate date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"HH:mm:ss"];
NSString *newDateString = [outputFormatter stringFromDate:now];
NSLog(@"newDateString %@", newDateString);
[outputFormatter release];
Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
6

You are, in fact, on the right track. Use

NSDate *date = [NSDate date];

to get the current date and time. Use NSDateFormatter to format it. See this link for a how-to on date and time formatting.

For your situation, you could do this:

NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"%H:%M:%S"];
NSString *timeString = [formatter stringFromDate:date];
Community
  • 1
  • 1
Aaron
  • 6,988
  • 4
  • 31
  • 48
5
NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init];

[DateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];  
NSLog(@"%@",[DateFormatter stringFromDate:[NSDate date]]);
David
  • 208,112
  • 36
  • 198
  • 279
user3119237
  • 51
  • 1
  • 2