5

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

Luda
  • 7,282
  • 12
  • 79
  • 139
  • Use another init for `Text` like [init(:format:)](https://developer.apple.com/documentation/swiftui/text/init(_:format:)) or [init(:formatter:)](https://developer.apple.com/documentation/swiftui/text/init(_:formatter:)-1v7mr) – Joakim Danielson Dec 27 '22 at 13:50
  • @JoakimDanielson But then I won't have the functionality of progressing time that the .timer gives me. Is there a way to combine both? – Luda Dec 28 '22 at 10:13
  • But if you style something as a timer (that is a counter) does it makes sense to show AM/PM since it is a duration? Shouldn't you use `.time` then if it is the actual time you want to show? – Joakim Danielson Dec 28 '22 at 11:31
  • @JoakimDanielson The reason I used the timer format is so I won't drain the budget for the widget refreshes as it is written here: https://stackoverflow.com/questions/64053733/updating-time-text-label-each-minute-in-widgetkit – Luda Jan 01 '23 at 08:26
  • I understand but I think you will have to accept that if you use `.timer` then am/pm makes no sense so you can’t format the output that way. – Joakim Danielson Jan 01 '23 at 08:41
  • @JoakimDanielson I might accept it in the near future. But maybe some alternative approach will surface in answers and comments... – Luda Jan 01 '23 at 09:23

1 Answers1

-1

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

piotdemi
  • 9
  • 1
  • But then I won't have the functionality of progressing time that the .timer gives me. Is there a way to combine both? – Luda Dec 28 '22 at 10:14
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 29 '22 at 11:37