Current and Updating time in iOS?
Like to share this simple code example. Just put this any where in your myClass code.You May find more formatting examples > Format String for the iPhone NSDateFormatter.
// Get current date timeNSDate *currentDateTime = [NSDate date];// Instantiate a NSDateFormatterNSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// Set the dateFormatter format//[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];// or this format to show day of the week Sat,11-12-2011 23:27:09[dateFormatter setDateFormat:@"EEE,MM-dd-yyyy HH:mm:ss"];// Get the date time in NSStringNSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime];NSLog(@"%@", dateInStringFormated);// Release the dateFormatter[dateFormatter release];
Use this code in viewDidLoad or viewWillAppear
-(void)callUpdate{NSTimer *timer = [[NSTimer alloc]initWithFireDate:[NSDate date] interval:0.1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];}-(void)updateTimer{NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];[dateformatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];NSString *dateInStringFormated=[dateformatter stringFromDate:[NSDate date]];label.text = dateInStringFormated;}
or else just alloc the timer in the viewDidLoad or viewWillAppear and when you need to stop the timer use
[timer invalidate];