How to Get Current Time in Swift

To get the current time in Swift:

  1. Choose a date.
  2. Grab the hour, minute, and the second using calendar’s time components.
  3. Display the time by grouping the time components.

For example, let’s show what time it is right now in the console:

import Foundation

// 1. Choose a date
let today = Date()

// 2. Pick the date components
let hours   = (Calendar.current.component(.hour, from: today))
let minutes = (Calendar.current.component(.minute, from: today))
let seconds = (Calendar.current.component(.second, from: today))

// 3. Show the time
print("\(hours):\(minutes):\(seconds)") 

Output:

11:59:32

Conclusion

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

50 Swift Interview Questions

iOS Development Tips

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.