Swift – Get Current Date Only
To get only current date, containing day, month and year, 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 date (day, month and year).
Example
In the following program, we will use Date and DateFormatter to get only the date containing day, month and year. We shall format the date as dd.MM.yyyy
, where day, month and year are separated by dot.
main.swift
</>
Copy
import Foundation
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let result = dateFormatter.string(from: date)
print(result)
Output
We can change the resulting date format by assigning required format string to dateFormat
property.
Conclusion
In this Swift Tutorial, we learned how to get only the current date from Date
value in Swift.