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.
This Swift code imports the Foundation framework, which provides fundamental data types, collections, and operating-system services to the Swift programming language.
The code then proceeds to:
- 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.
- 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.
- 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, which 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.
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
- Artificial Intelligence2023.03.14Best AI Tools of 2023 (Save Time & Boost Productivity)
1 thought on “How to Get Current Time in Swift (Quick 3-Step Guide)”
Reading your article helped me a lot and I agree with you. But I still have some doubts, can you clarify for me? I’ll keep an eye out for your answers.