0

Im building an app in Swift that gets data from an API then displays it in a more appealing/user readable format.

The API returns an Int that represents time in a 24hr format that looks like this:

2200

So, what im looking to do is conversion like this:

2100  ->  9:00pm

Does anyone know how to accomplish this in Swift?

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
zlyt
  • 259
  • 5
  • 23
  • 1
    Have you done any research yourself? Several possible routes here, one is to use DateComponents and DateComponentsFormatter. You could [start here](https://developer.apple.com/documentation/foundation/dates_and_times) with your research – Joakim Danielson Jan 30 '20 at 20:29
  • After parsing your date string you can use this post https://stackoverflow.com/a/28347285/2303865 to show your date or just the time reflecting the user’s device locale and settings – Leo Dabus Jan 30 '20 at 21:19

1 Answers1

0

You can use

let date = Date()//Pass your date here either.
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
let time = formatter.string(from: date)

Hope that helps.

B25Dec
  • 2,301
  • 5
  • 31
  • 54
  • This is a 12h format but would have many issues involved. One of them is the leading zero but there would be more issues besides that. – Leo Dabus Jan 30 '20 at 20:35
  • Agreed his server should send time in a format by which he can first convert it in a proper date string (which can be understood by Date) then pass in above func to get it done. – B25Dec Jan 30 '20 at 20:48
  • I am taking about setting the date formatter locale to en_US_POSIX to avoid it reflecting the devices locale and settings. You should set its calendar to iso8601 as well – Leo Dabus Jan 30 '20 at 20:59
  • Note that OP asked how to display it in a more appealing/user readable format. Your answer doesn’t take care of it. The proper way to do what OP asked is to use `DateFormatter`‘s `timeStyle` To display it localized using the user device locale and settings instead of setting a fixed `dateFormat` As shown in your post. – Leo Dabus Jan 30 '20 at 21:14
  • Take a look at this post https://stackoverflow.com/questions/28332946/how-do-i-get-the-current-date-in-short-format-in-swift/28347285 – Leo Dabus Jan 30 '20 at 21:17