iOS_User
iOS_User

Reputation: 1382

how can i display current time on a label?

how can i display current time on a label iphone?

Upvotes: 4

Views: 6193

Answers (4)

Himanshu padia
Himanshu padia

Reputation: 7712

Objective-C

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd.MM.YY HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:currDate];

yourLabel.text=dateString

Swift 3.0

var currDate = Date()
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.YY HH:mm:ss"
var dateString = dateFormatter.string(fromDate: currDate)
yourLabel.text! = dateString

Upvotes: 8

schaechtele
schaechtele

Reputation: 1130

If you have to format your date before showing it use the NSDateFormatter class.

http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

Upvotes: 0

sagarkothari
sagarkothari

Reputation: 24810

Ok. Here is something like you need.

Place an IBOutlet Label on your .h file of your view controller & connect in .xib file.

Now, just place following code in your .m file of view controller.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // your label text is set to current time
    lblTime.text=[[NSDate date] description];
    // timer is set & will be triggered each second 
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];

}
// following method will be called frequently.
-(void)showTime{
    lblTime.text=[[NSDate date] description];
}

Upvotes: 7

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

Use an NSTimer to trigger regular calls to a method that updates the label.

Upvotes: 0

Related Questions