0

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.

  • you can set your date formatter's `defaultDate = Date()` if you want to zero out the milliseconds as well you can use `dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())` – Leo Dabus Jan 12 '22 at 23:33
  • this might help you as a reference on how you should parse your time string https://stackoverflow.com/questions/68369889/swift-compare-between-time/68371345#68371345 – Leo Dabus Jan 12 '22 at 23:41

1 Answers1

2

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)!
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • hm so about your first block. This was something that I had in mind, but I was wondering if there was a way to not have to split up the string to get the individual int values? If not, then I guess I'll be splitting the string then. – harvey_burns Jan 12 '22 at 23:05
  • 2
    @harvey_burns Well, as it turns out (and if you see my last update), you can convert a time based `String` to `Date` using `DateFormatter`, once you have the `Date`, then you can just run it through the other `DateFormatter`. Since I don't know what values you have to start with, I'm just covering my bases – MadProgrammer Jan 12 '22 at 23:11