Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1637785
  • 博文数量: 311
  • 博客积分: 7778
  • 博客等级: 少将
  • 技术积分: 4186
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-09 19:59
个人简介

蓝点工坊(http://www.bluedrum.cn) 创始人,App和嵌入式产品开发。同时也做相应培训和外包工作。 详细介绍 http://pan.baidu.com/s/1y2g88

文章存档

2012年(3)

2011年(115)

2010年(170)

2009年(23)

分类: 嵌入式

2010-12-23 17:47:48

Andrew Huang

我在测试一个简单的时间显示小程序,在其定时器响应代码定时用把当前时间显示在屏幕上,如下代码


NSDate* now = [NSDate date];  

int hour = 23 - [[now dateWithCalendarFormat:nil timeZone:nil] hourOfDay]; 

int min = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] minuteOfHour]; 

 int sec = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] secondOfMinute];  

countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec];


但有编译错误:
  Compiler Warning:  warning 'NSDate' many not respond to '-dateWithCalendarFormat:timeZone'

错误原因
这里提示没有这个方法。查找一下发现是因为在NSDate在MacOS 10.5.x编译的原因,在10.6.x没有这个问题。
因此必须改写代码.

解决办法:
用NSDateFormatter来格式化输出.

以下是等效代码




//实例化一个NSDateFormatter对象 

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 

 //设定时间格式,这里可以设置成自己需要的格式 

 [dateFormatter setDateFormat:@" HH:mm:ss"]; 

 //用[NSDate date]可以获取系统当前时间 

 countdownLabel.text = [dateFormatter stringFromDate:[NSDate date]]; 

 //释放对象 

 [dateFormatter release];


扩展话题
  对于如何取出时间里的数字又如何操作了呢?
这里的建议是采用NSCalendar 和 NSDateComponents.对象来改写
参考


  


阅读(2333) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~