Skip to content

emma-k-alexandra/RelativeDateView

Repository files navigation

RelativeDateView

An autoupdating SwiftUI view for displaying time relative to a Date.

Important!

Apple implemented the relative Text.DateStyle in 2020 for iOS 14, macOS 11, etc. See if this DateStyle solves your use case first!

Examples

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.

Contents

Requirements

  • Swift 5.1+
  • macOS 10.15+, iOS 13+, tvOS 13+, watchOS 6+

Installation

Swift Package Manager

dependencies: [
    .package(url: "https://github.com/emma-k-alexandra/RelativeDateView.git", from: "3.1.1")
]

Usage

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.

Dependencies

  • DateHelper

Contact

Feel free to email questions and comments to emma@emma.sh

License

RelativeDateView is released under the MIT license. See LICENSE for details.