Eric Brotto
Eric Brotto

Reputation: 54281

Get current time on the iphone in a chosen format

The following should give me an NSDate object of 9:30:

NSString *dateString = @"09-30";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh-mm"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];

How do I get the current time in the same format?

Upvotes: 5

Views: 25228

Answers (5)

Tendulkar
Tendulkar

Reputation: 5540

NSDate *today = [[NSDate alloc] init];
NSLog(@"today is :%@", today);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh-mm:ss"];
NSString *timeString = [dateFormatter stringFromDate:today];

NSLog(@"%@", timeString);

Upvotes: 1

Denis
Denis

Reputation: 6413

NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh-mm"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];

Upvotes: 15

bryanmac
bryanmac

Reputation: 39306

NSDate alloc init will create a date with the current time. Then, you can use NSDateFormatter stringFromDate for format and present that date.

This:

NSDate *date = [[NSDate alloc] init];
NSLog(@"%@", date);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh-mm"];
NSString *dateString = [dateFormatter stringFromDate:date];

NSLog(@"%@", dateString);

Outputs:

2011-12-05 07:20:02.994 Craplet[1706:707] 2011-12-05 12:20:02 +0000
2011-12-05 07:20:02.995 Craplet[1706:707] 07-20

Upvotes: 1

Nareshkumar
Nareshkumar

Reputation: 2351

NSDate *currentDate =[NSDate date];
//Your formatter goes here.
NSString *currentTime = [dateFormatter stringFromDate:currentDate];

Upvotes: 0

Mathieu Hausherr
Mathieu Hausherr

Reputation: 3485

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh-mm"];
NSDate *currentDate = [NSDate date];
NSString *currentDateString = [dateFormatter stringFromDate:currentDate];

Upvotes: 2

Related Questions