Get the Time with Swift
by Alexandra Kropova from Mammoth InteractiveWant to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.To get the current hour, use the following Swift 5.5 code:
func getTime() -> String { let formatter = DateFormatter() formatter.timeStyle = .short let dateString = formatter.string(from: Date()) return dateString }
Understanding this function:
The function name is getTime. The function takes in no parameters (arguments). We instantiate a DateFormatter object, which can format a Date (which includes date and time) into a String. You must set the timeStyle of the DateFormatter to .short or .long. Otherwise, nothing will appear in your app. The short time style shows the time, for example, as “3:20 PM”. The long time style shows the time, for example, as “11:20:14 AM PDT”. Suggest more solutions or ask a question in the comments below.Want to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.