如何格式化 elapsedTime 从 00:00:00 开始而不是 Swift 中的默认 07:00:00
How to format elapsedTime start at 00:00:00 instead of the default 07:00:00 in Swift
我找不到使用 QuartzCore 让秒表显示从 00:00:00 开始的方法。它总是从 07:00:00.
开始
有没有办法将开始时间格式化为 00:00:00?代码如下。
谢谢!!
Class:
import Foundation
import QuartzCore
class StopWatch: NSObject{
private var displayLink: CADisplayLink!
private let formatter = DateFormatter()
var callback: (() -> Void)?
var elapsedTime: CFTimeInterval!
override init() {
super.init()
self.displayLink = CADisplayLink(target: self, selector: #selector(tick(sender:)))
displayLink.isPaused = true
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
self.elapsedTime = 0.0
formatter.dateFormat = "HH:mm:ss"
}
convenience init(withCallback callback: @escaping () -> Void) {
self.init()
self.callback = callback
}
deinit {
displayLink.invalidate()
}
func tick(sender: CADisplayLink) {
elapsedTime = elapsedTime + displayLink.duration
callback?()
}
func elapsedTimeAsString() -> String {
return formatter.string(from: Date(timeIntervalSinceReferenceDate:elapsedTime))
}
}
已更正,如下评论所述:
正如上面提到的评论者,这是一个时区问题,因为我位于 GMT +7。我添加了以下代码来解决问题:
formatter.timeZone = 时区(缩写:"GMT")!
我找不到使用 QuartzCore 让秒表显示从 00:00:00 开始的方法。它总是从 07:00:00.
开始有没有办法将开始时间格式化为 00:00:00?代码如下。
谢谢!!
Class:
import Foundation
import QuartzCore
class StopWatch: NSObject{
private var displayLink: CADisplayLink!
private let formatter = DateFormatter()
var callback: (() -> Void)?
var elapsedTime: CFTimeInterval!
override init() {
super.init()
self.displayLink = CADisplayLink(target: self, selector: #selector(tick(sender:)))
displayLink.isPaused = true
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
self.elapsedTime = 0.0
formatter.dateFormat = "HH:mm:ss"
}
convenience init(withCallback callback: @escaping () -> Void) {
self.init()
self.callback = callback
}
deinit {
displayLink.invalidate()
}
func tick(sender: CADisplayLink) {
elapsedTime = elapsedTime + displayLink.duration
callback?()
}
func elapsedTimeAsString() -> String {
return formatter.string(from: Date(timeIntervalSinceReferenceDate:elapsedTime))
}
}
已更正,如下评论所述: 正如上面提到的评论者,这是一个时区问题,因为我位于 GMT +7。我添加了以下代码来解决问题:
formatter.timeZone = 时区(缩写:"GMT")!