0

I'm trying to take in a time value as a string, then have a notification use that value for it's trigger to display. My issue is the notification takes in this format to set it's time:

    var dateComponents = DateComponents()
    dateComponents.hour = 06
    dateComponents.minute = 30

    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

and I'm currently implementing the following from this Stack Overflow post to separate out the int values from the string.

let time = "7:30" //Would like to pass in "7:30 PM" instead
let components = time.characters.split { $0 == ":" } .map { (x) -> 
Int in return Int(String(x))! }

let hours = components[0]
let minutes = components[1]

Neither allow for any AM/PM information. Is there a simple way to take in the time of day and set a notification up based on that input? Thanks!

moosgrn
  • 379
  • 3
  • 13

1 Answers1

1

If you want to work with strings then you can do an extra split on " " and check if you have AM or PM and based on that adjust the hour part

let time = "7:30 PM" 
let firstSplit = time.split(separator: " ")
let components = firstSplit[0].split(separator: ":").compactMap { Int($0) }
let isPM = firstSplit[1] == "PM"
let hours = components[0] + (isPM ? 12 : 0)
let minutes = components[1]

Of course some safety checks might be needed to verify that the input string is correct.

If you on the other hand want to work with Date and DateComponents a cleaner solution can be had like this

let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.locale = Locale(identifier: "en_US_POSIX")

if let parsedTime = formatter.date(from: time) {
    let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: parsedTime)
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52