Swift – Get Current Time Only

To get only current time, containing hour, minute and second, use Date and DateFormatter.

Date returns current point in time, while DateFormatter with specified dateFormat formats this Date value to required format, like in this case returning only time (hour, minute and second).

Example

In the following program, we will use Date and DateFormatter to get only the time containing hour, minute and second. We shall format the date as HH:mm:ss, where hour, minute and second are separated by semi-colon.

main.swift

</>
Copy
import Foundation

let date = Date()
let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "HH:mm:ss"

let result = dateFormatter.string(from: date)
print(result)

Output

Swift - Get Current Time Only

We can change the resulting time format by assigning required format string to dateFormat property.

Conclusion

In this Swift Tutorial, we learned how to get only the current time from Date value in Swift.