TrendRadars > Technology > Develop > SwiftUI, WidgetKit: Format date with timer style
SwiftUI, WidgetKit: Format date with timer style
SwiftUI, WidgetKit: Format date with timer style,I have a working clock widget. To achieve that, I have created a timeline that updates once a day. func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) { ...

SwiftUI, WidgetKit: Format date with timer style

I have a working clock widget. To achieve that, I have created a timeline that updates once a day.

func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {        let midnight = Calendar.current.startOfDay(for: Date())        let nextMidnight = Calendar.current.date(byAdding: .day, value: 1, to: midnight)!        let entries = [SimpleEntry(date: midnight)]        let timeline = Timeline(entries: entries, policy: .after(nextMidnight))        completion(timeline)    }

The widget shows the clock like this:

var body: some View {             VStack {         Text(entry.date, style: .timer)                 }         }

I chose this approach over creating a timeline of entries every minute, as I read in the documentation that the system doesn’t promise to update the widget as requested, but according to a budget.

The label shows something like this:

14:30:25

How can I make it show

2:30 PM instead

<——-Answers———->

You can use DateFormatter or directly with Text.init(_:formatter:).Also you can use Text.init(_:format:)