IOS---如何获取当前的日期和时间,并显示
创建两个UILable: Lable1,Lable2.创建好IBOutlate并连线, 然后用如下方法:
-(void)updateLabel {
NSDate* now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
unsigned
int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit;
NSDateComponents *dd = [cal components:unitFlags fromDate:now];
int y = [dd year];
int m = [dd
month];
int d = [dd day];
int hour = [dd hour];
int min = [dd minute];
int sec = [dd second];
Lable1.text
= [NSString stringWithFormat:@"2d%:2d%:2d%",y,m,d];
Lable2.text =[NSStrinstringWithFormat:@"2d%:2d%:2d%",hour,min,sec];
}
- (void)onTimer {
[viewController updateLabel];
}
在AppDeletate.m文件中增加如下方法:
- (void)applicationDidFinishLaunching:(UIApplication
*)application {
timer =
[NSTimer
scheduledTimerWithTimeInterval:(1.0)
target:self selector:@selector(onTimer) userInfo:nil
repeats:YES];
[window addSubview:viewController.view];
[window
makeKeyAndVisible];
}