Currently I use Date(timeIntervalSince1970: dateDouble).relativeTime
to get relative time. And get string like "2 hours ago". Is there a way to get localized string?
In the wild world of 2019 SwiftUI development, lots of things aren't documented. One such thing I ran into recently was the usage of RelativeDateTimeFormatter in a Text view. RelativeDateTimeFormatter is a new formatter which is available in iOS 13+ and macOS 10.15+.
SwiftUI declares a custom string interpolation (which is a new feature in Swift 5) called LocalizedStringKey.StringInterpolation (also undocumented at the time of writing, like 59.4% of SwiftUI) which allows you to write Text views with formatters like so: Text("My String (myVariable, formatter: myFormatter)")
This formatter formats dates relative each other as well as relative DateComponents - its output looks like "one minute ago" or "two minutes from now". Most blog posts about RelativeDateTimeFormatter show its usage like this:
let timeInterval = 0
let date = Date(timeIntervalSinceNow: timeInterval)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .medium
dateFormatter.locale = Locale.current
dateFormatter.doesRelativeDateFormatting = true
print(dateFormatter.string(from: date)) // Today
// modifying locale
dateFormatter.locale = Locale(identifier: "fr_FR")
print(dateFormatter.string(from: date)) // aujourd’hui
check out https://developer.apple.com/documentation/foundation/dateformatter/1415848-doesrelativedateformatting
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With