1

I've inserted an timer, so the time changes according to the system clock. the problem is, its displaying in numbers without am/pm like(12:33). please guide me to solve this problem.

This is the code I used to display the text.

@State var endTime = Date()
var body: some View {
Text("Ends - \(myViewModel.timeString(date: endTime))")
 .onAppear(perform: {let _ = self.updatedEndTime})
}

This is code I used to update timer according to the system time.

var updateEndTime: Timer {
    Timer.scheduledTimer(withTimeInterval: 0, repeats: true,
       block: {_ in
        self.endTime = Date() + myViewModel.player.duration - myViewModel.player.currentTime
          })
    }

My view model code

var timeFormat: DateFormatter {
    let formatter = DateFormatter()
    formatter.dateFormat = "hh:mm"
    return formatter
}

func timeString(date: Date) -> String {
     let time = timeFormat.string(from: date)
     return time
}
stackich
  • 3,607
  • 3
  • 17
  • 41
davede3103
  • 67
  • 1
  • 9

1 Answers1

0

You can set amSymbol and pmSymbol on DateFormatter and use the a symbol to print it.

lazy var timeFormat: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "h:mm a"
        formatter.amSymbol = "AM"
        formatter.pmSymbol = "PM"
        return formatter
}()

In my locale (US), even without setting amSymbol and pmSymbol, they appear as "AM"/"PM", but I'm not sure that's true across all locales.

jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • its expensive creating DateFormatter every time whenever a time need! – YodagamaHeshan Feb 11 '21 at 08:41
  • Updated to make it lazy init. Note that the original was just adjusting OP’s code. – jnpdx Feb 11 '21 at 08:56
  • @jnpdx it decreases the performance. Better way is to use the solution which I have commented in the question .(since this question is closed ) – YodagamaHeshan Feb 11 '21 at 12:58
  • Calling it once with lazy will not decrease performance. Your way works as well, but is ultimately less flexible if a more custom format is needed. – jnpdx Feb 11 '21 at 14:31