NSTimer 倒计时标签
它将不断倒计时并更新当前时间。任何人都知道如何解决这个问题?我不明白 NStimer 如何识别这样的日期格式: 20110803 23:59:59
It will keep counting down and updating the current time. Anyone has any idea how to approach this problem? I don't see how the NStimer will recognize the date format like this:
20110803 23:59:59
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
查找
NSDateFormatter
。您可以指定格式字符串 (-[setDateFormat:]
),以便将NSDate
和NSString
转换为 AND。当转换回倒计时视图时,您可能需要使用
NSDateComponents
和NSCalendar
获取倒计时标签所需的部分(而不是NSDateFormatter
)。您可以执行以下操作:这将为您计算所有单位差异(相对于设备当前配置的日历设置)。
您可以通过
[countdown day]
或[countdown hour]
等调用取回组件。Look up
NSDateFormatter
. You can specify a format string (-[setDateFormat:]
)that lets you convert to AND fromNSDate
andNSString
.When converting back to your countdown view, you may want to use
NSDateComponents
andNSCalendar
to get the pieces you need for your countdown label (instead ofNSDateFormatter
). You could do something like:This will calculate all the unit differences for you (with respect to the device's currently configured calendar settings).
You can get the components back with a call like
[countdown day]
or[countdown hour]
.您可以通过像这样使用
NSDateFormatter
从字符串中获取NSDate
对象来轻松获取日期。You can get the date easily by using
NSDateFormatter
like this to get aNSDate
object from your string.您可以使用 NSDateformatter 类将日期从 NSString 转换为 NSDate。
现在,为了倒计时,您使用
NSTimer
类每隔一秒触发一次,然后您可以通过以下方式获取当前日期和date
变量之间的秒数差异:只需使用timeIntervalSinceDate
。现在您已经得到了以秒为单位的差异,您可以将其转换为您想要显示的任何格式。
You could convert the date from NSString to NSDate by using the NSDateformatter class.
Now, in order to count down, you use the
NSTimer
class to fire every one second, then you can get the difference in seconds between the current date and yourdate
variable by simply usetimeIntervalSinceDate
.Now that you have the difference in seconds, you convert it to whatever format you wish to display.
我没有深入研究这个问题,所以很抱歉,如果我的回答有点不恰当。
在这种情况下我会使用 NSDate。使用 NSDateFormatter 我会将 xml 文本数据转换为 NSDate。当 NSTimer 的每个刻度正确时,更改 NSDate 的值。
还有一些代码,因为 NSDateFormatter 的符号有时会造成混乱:
这是用于从 xml 读取的。对于在勾选时更改 NSDate 的值,您可以查看 NSDate 的文档。为了显示标签中的值,我将通过算术计算每个值并在随意的 NSString 的帮助下显示它:
I didn't drill down into this problem deeply, therefore sorry, if my answer is a bit unappropriate.
In this case I would use NSDate. Using NSDateFormatter I would convert text data of xml to NSDate. Changing the value of NSDate, when every tick of NSTimer, properly.
And a bit of code, 'cause the symbols of NSDateFormatter sometimes create mess:
This is for reading from xml. For changing value of NSDate when tick you can see the doc of NSDate. And for display the value in label I would arithmetically calculate every value and show it with the help of casual NSString: