TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How to display difference between some Date and now?

Forums > SwiftUI

I have this extension here that returns a formatted string just like how I want it:

extension Date {
    func formattedTimeUntilNow() -> String {
        let now = Date()
        let different = Calendar.current.dateComponents([.year, .day, .hour, .minute, .second], from: self, to: now)
        if different.year != 0 {
            let differentDay = Calendar.current.dateComponents([.day], from: self, to: now)
            return "\(String(format: "%.1f", floor(Double(10 * differentDay.day!) / 365.0) / 10))y"
        }
        if different.day != 0 {
            return "\(different.day!)d"
        }
        if different.hour != 0 {
            return "\(different.hour!)h"
        }
        if different.minute != 0 {
            return "\(different.minute!)m"
        }
        return "\(different.second ?? 0)s"
    }
}

How do I display this string in a Text view and letting it update automatically (for example, if the date is from 10 seconds ago I want the Text view to display 10s, 11s, 12s and so on).

2      

Hi, why don't you try Text initializers as follows:

Just use the date var you need in below code just to see the difference between time changes from date up to now

Text(Date().addingTimeInterval(-6000), style: .offset)            
Text(Date().addingTimeInterval(-6000), style: Text.DateStyle.relative)           
Text(Date().addingTimeInterval(-6000), style: Text.DateStyle.timer)”

2      

But I want it in that short form (1h, 23m, 267d, 1.6y and so on)

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.