Swift – Get Current Time

In this tutorial, we will learn how to get the current time in Swift. We will explore the Date class, use DateFormatter to extract and format the time, and write a complete program with some examples.


Getting the Current Time in Swift

In Swift, you can use the Date class to get the current time. By default, Date() retrieves both the current date and time. To specifically extract and format the time, we use the DateFormatter class.

Here’s a simple example to print the current time:

</>
Copy
let currentTime = Date()
print("Current Time: \(currentTime)")

However, this prints the time in the default format along with the date. To display only the time in a human-readable format, we use DateFormatter.


Formatting the Current Time

The DateFormatter class allows you to extract and format the time. You can specify a custom format using dateFormat.

Here’s an example to format the current time:

</>
Copy
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm:ss"
let formattedTime = timeFormatter.string(from: currentTime)
print("Formatted Time: \(formattedTime)")

Explanation:

  • HH: Represents hours in 24-hour format.
  • mm: Represents minutes.
  • ss: Represents seconds.
  • timeFormatter.string(from: currentTime): Converts the Date object into a formatted string for time.

Using Predefined Styles for Time

The DateFormatter class also provides predefined styles for time, such as .short and .medium.

Here’s an example:

</>
Copy
let shortTimeFormatter = DateFormatter()
shortTimeFormatter.timeStyle = .short
print("Short Time Style: \(shortTimeFormatter.string(from: currentTime))")

let mediumTimeFormatter = DateFormatter()
mediumTimeFormatter.timeStyle = .medium
print("Medium Time Style: \(mediumTimeFormatter.string(from: currentTime))")

Explanation:

  • .short: Displays a concise version of the time, e.g., 2:53 PM.
  • .medium: Displays a more detailed version of the time, e.g., 2:53:29 PM.

Complete Swift Program

Here’s the complete Swift program to demonstrate getting and formatting the current time:

main.swift

</>
Copy
import Foundation

// Get the current time
let currentTime = Date()
print("Current Time: \(currentTime)")

// Format the time using a custom format
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm:ss"
let formattedTime = timeFormatter.string(from: currentTime)
print("Formatted Time: \(formattedTime)")

// Display time in predefined styles
let shortTimeFormatter = DateFormatter()
shortTimeFormatter.timeStyle = .short
print("Short Time Style: \(shortTimeFormatter.string(from: currentTime))")

let mediumTimeFormatter = DateFormatter()
mediumTimeFormatter.timeStyle = .medium
print("Medium Time Style: \(mediumTimeFormatter.string(from: currentTime))")

Output

Current Time: 2024-11-21 00:24:21 +0000
Formatted Time: 05:54:21
Short Time Style: 5:54 AM
Medium Time Style: 5:54:21 AM
Program ended with exit code: 0

Xcode Screenshot

Swift Program to Get Current Time