To get the current time in Swift:
- Choose a date.
- Grab the hour, minute, and the second using calendar’s time components.
- 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)")
A Deeper Dive
Let’s take a closer look at the above Swift code to understand what it does!
This Swift code imports the Foundation framework, which provides fundamental data types, collections, and operating-system services to the Swift programming language.
Then the code does the following:
#1 Create a constant variable named “today” and set it to the current date and time using the Date() initializer.
The Date type represents a specific point in time by the Foundation framework.
#2 Extract the current hour, minute, and second components from the “today” date using the Calendar.current component method.
This method returns the specified component of a given date in the current calendar, which is based on the user’s preferred calendar and region settings.
The extracted components are stored in the “hours”, “minutes”, and “seconds” constants, respectively.
#3 Print the current time in the format “HH:MM:SS“.
The values of the “hours”, “minutes”, and “seconds” constants are interpolated into a string using the string interpolation syntax of Swift. This uses the “()” syntax to evaluate and insert the value of a variable or expression into a string.
Thanks for reading. I hope you find it useful.