How to get Current Date and Time in Swift with examples
This tutorial explains how to get the Current Date and time in Swift with examples.
- Current Date and time in Swift using the
Date()
function - current Date in Short Format using
DateFormatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy")
- get Time without Date using the
DateFormatter.long
property
How to get the Current Date and time in Swift?
The Date
class provides access to the date and time of the UTC zone.
Here is an example
import Foundation
let date = Date()
print(date)
Output
2022-10-30 11:16:49 +0000
The date object returns the format as per the code running on the device or web.
import Foundation
/runpkg/Sources/runpkg/main.swift:1:12: error: cannot find 'Date' in scope
let date = Date()
How to get the current Date in Short Format in Swift
Swift provides DateFormatter
that formats the string with the given format string. DateFormatter.setLocalizedDateFormatFromTemplate
accepts MM/dd/yyyy
import Foundation
let date = Date()
print(date)
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy")
let shortDate = dateFormatter.string(from: date)
print(shortDate)
Output
07/03/2022
Similarly, you can set DateFormatter.dateStyle
to short as given below
import Foundation
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
dateFormatter.dateStyle = .short
let shortDate = dateFormatter.string(from: date)
print(shortDate)
Output:
7/3/22
How to get Time without Date in swift with an example
DateFormatter contains two properties, change it as given below
timeStyle
to.long
dateStyle
to.none
Here is an example
import Foundation
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .long
dateFormatter.dateStyle = .none
let timeOnly = dateFormatter.string(from: date)
print(timeOnly)
Output:
6:03:27 AM GMT