Skip to content

Instantly share code, notes, and snippets.

@prafullakumar
Created May 31, 2020 15:45
Show Gist options
  • Save prafullakumar/64a01b33d6987a9e2df7056084f682ba to your computer and use it in GitHub Desktop.
Save prafullakumar/64a01b33d6987a9e2df7056084f682ba to your computer and use it in GitHub Desktop.
import SwiftUI
import Combine
final class CurrentTime: ObservableObject {
@Published var seconds: TimeInterval = CurrentTime.currentSecond(date: Date())
private let timer = Timer.publish(every: 0.2, on: .main, in: .default).autoconnect()
private var store = Set<AnyCancellable>()
init() {
timer.map(Self.currentSecond).assign(to: \.seconds, on: self).store(in: &store)
}
private static func currentSecond(date: Date) -> TimeInterval {
let components = Calendar.current.dateComponents([.year, .month, .day], from: date)
let referenceDate = Calendar.current.date(from: DateComponents(year: components.year!, month: components.month!, day: components.day!))!
return Date().timeIntervalSince(referenceDate)
}
}
struct ContentView: View {
@ObservedObject var time = CurrentTime()
var body: some View {
return ZStack {
Text("\(time.seconds)")
}.frame(width: 200, height: 200, alignment: .center)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment