An autoupdating SwiftUI view for displaying time relative to a Date
.
Apple implemented the relative
Text.DateStyle
in 2020 for iOS 14, macOS 11, etc. See if this DateStyle solves your use case first!
For a Date
that's 1 minute in the past, display "1 minute ago".
For a Date
that's 2 weeks in the future, display "in 2 weeks".
For a Date
that's now, display "right now".
Text is fully customizable, and display automatically updates as the time delta between now and your date changes.
- Swift 5.1+
- macOS 10.15+, iOS 13+, tvOS 13+, watchOS 6+
dependencies: [
.package(url: "https://github.com/emma-k-alexandra/RelativeDateView.git", from: "3.1.1")
]
import RelativeDateView
struct ContentView: View {
@State private var isFuture = true
@State private var date = Date().addingTimeInterval(2 * 60)
var body: some View {
if self.isFuture {
return AnyView(
RelativeDateView(
date: $date,
format: [
.nowFuture: "ARR",
.nowPast: "BRD",
.secondsFuture: "1",
.secondsPast: "BRD",
.oneMinuteFuture: "1",
.minutesFuture: "%.f"
],
isFuture: $isFuture
) { text in
text.bold()
}
)
} else {
return AnyView(Text("It's in the past"))
}
}
}
For details on format
, see DateHelper.
- DateHelper
Feel free to email questions and comments to emma@emma.sh
RelativeDateView is released under the MIT license. See LICENSE for details.