【发布时间】:2018-02-26 02:08:40
【问题描述】:
我正在使用 Swift 4 编写一个应用程序。此应用程序首先获取当前设备时间并将其放入标签 (currentTimeLabel) 中,格式为 HH:mm。
它还从 Firebase 数据库中获取不同时区的时间作为字符串,并将其放入两个标签(currentSharedTimeLabel 和 timeReceivedFromServerLabel)中,格式也是 HH:mm。从服务器检索的数据还包括秒数。显然,这第二次并没有改变——但我希望它表现得像用户期望的那样,即我想每秒添加一秒到服务器时间。
为此,我首先使用以下代码将共享时间从字符串更改为格式化时间:
let isoDate = timeReceivedFromServerLabel.text
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let mathDate = dateFormatter.date(from: isoDate!)
然后我想运行一个函数,它每秒向mathDate 添加一秒并将结果放入currentSharedTimeLabel。你能告诉我如何实现这一目标吗?
目前,完全没有效果,我正在做:
for i in 0..<1314000 {
let j = i + 1
print(i, j)
let newCalcTime = mathDate?.addingTimeInterval(TimeInterval(j))
currentSharedTimeLabel.text = ("\(newCalcTime)")
print("\(String(describing: newCalcTime))")
我对此有点不知所措,如果能提供任何帮助,我将不胜感激。
(我希望我已经把我的问题说清楚了,不要因为缺乏或肤浅的信息而让你不高兴)。
编辑 2: 数据库观察者代码(更新 Cocoapods 后)
// SUBMIT BUTTON
let submitAction = UIAlertAction(title: "Submit", style: .default, handler: { (action) -> Void in
let textField = alert.textFields![0]
self.enterSharingcodeTextfield.text = textField.text
// SEARCHES FOR SHARING CODE IN DATABASE (ONLINE)
let parentRef = Database.database().reference().child("userInfoWritten")
parentRef.queryOrdered(byChild: "sharingcode").queryEqual(toValue: textField.text).observeSingleEvent(of: .value, with: { snapshot in
print(snapshot)
// PROCESSES VALUES RECEIVED FROM SERVER
if ( snapshot.value is NSNull ) {
// DATA WAS NOT FOUND
// SHOW MESSAGE LABEL
self.invalidSharingcodeLabel.alpha = 1
} else {
// DATA WAS FOUND
for user_child in (snapshot.children) {
【问题讨论】:
-
为什么要用
HH:mm:ss格式化它?你不是说是HH:mm的格式吗?是否要显示秒数?如果你不这样做,那么每分钟增加一分钟就可以了,对吧? -
@Sweeper 它来自服务器,格式为“07:30:22”的字符串,因此以秒为单位。我这样做是为了能够正确执行“每秒添加 1 秒”的计算。在向用户显示最终计算时间的标签中,最好只显示 HH:mm。
标签: swift nsdateformatter swift4 dateformatter