harvey_burns
harvey_burns

Reputation: 13

How to convert HH:mm:ss only to am/pm in swift?

So I have a time that's in string format HH:mm:ss (08:30:00 for example). I want to be able to convert it to 8:30 AM.

Normally it would be easy if I had the year,month,day to go along so it would be simple to do the conversions but in this case I don't need it.

My original plan was to get current Date() then assign the time to it then convert it to the new format of H:mm a but I haven't been able to do this successfully. Meaning I have only been able to convert it to a Date object that has year 1/1/2000 and the time is set in UTC.

Am I overthinking this? Is there an easier way without doing any conversions? I just want to be able to display the time in H:mm a format without altering any timezones.

Upvotes: 1

Views: 1683

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347332

You need to create a Date with the specified time value. For this, I'd simple create a new instance of Date and then use Calendar to set the time to the desired value

var date = Date()

let cal = Calendar.current
// Please note, this returns an optional, you will need to deal
// with, for demonstration purposes, I've forced unwrapped it
date = cal.date(bySettingHour: 8, minute: 30, second: 0, of: date)!

From there, you make use of a DateFormatter to format the result to a String

let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"

formatter.string(from: date)

Now, if you're starting with a String value (of HH:mm:ss), you can actually use a DateFormatter to parse it, for example...

let value = "08:30:00"
let parser = DateFormatter()
parser.dateFormat = "HH:mm:ss"
// Again, this is forced unwrapped for demonstration purposes
let parsedDate = parser.date(from: value)!

Upvotes: 3

Related Questions