Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get localized relative date Swift

Tags:

ios

swift

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?

like image 963
Sarah Jons Avatar asked Jul 17 '18 18:07

Sarah Jons


People also ask

What is relativedatetimeformatter in SwiftUI text view?

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+.

What is localizedstringkey in SwiftUI?

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)")

What does the relativedatetimeformatter look like?

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:


1 Answers

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

like image 180
nambatee Avatar answered Oct 18 '22 01:10

nambatee