Consider the code below...
The green box using style: .relative is updating the relative time continuously, but it has too much detail for my taste.
The red box using formatter: rFormatter has exactly the right detail but it doesn't update unless I force it to - maybe a timer or something?
How do I most efficiently combine the formatting I want with the continuous updating?
The green box using style: .relative is updating the relative time continuously, but it has too much detail for my taste.
The red box using formatter: rFormatter has exactly the right detail but it doesn't update unless I force it to - maybe a timer or something?
How do I most efficiently combine the formatting I want with the continuous updating?
Code Block struct ContentView: View { var relDate: Date { let comps = Calendar.current.dateComponents([.hour, .day, .month, .year], from: Date()) return Calendar.current.date(from: comps)! } let rFormatter = RelativeDateTimeFormatter() init() { rFormatter.dateTimeStyle = .named } var body: some View { VStack { Text(relDate, style: .relative) .padding() .background(Color(.green)) Text(relDate, formatter: rFormatter) .padding() .background(Color(.red)) } } }
I'm not sure if it would be the most efficient or not, but using Timer is one way that actually works.maybe a timer or something?
Code Block struct ContentView: View { var relDate: Date { let comps = Calendar.current.dateComponents([.hour, .day, .month, .year], from: Date()) return Calendar.current.date(from: comps)! } let rFormatter: RelativeDateTimeFormatter = { let formatter = RelativeDateTimeFormatter() formatter.dateTimeStyle = .named return formatter }() let timer = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect() @State var relDateText = "" var body: some View { VStack { Text(relDate, style: .relative) .padding() .background(Color(.green)) Text(relDateText) .padding() .background(Color(.red)) } .onReceive(timer, perform: {_ in self.relDateText = rFormatter.string(for: relDate)! }) } }