Converting Dates To Formatted Strings Easily in Swift
No more date formatters and lines of code to convert
Getting dates as strings in Swift is not a rare task. The format of the presented date depends on the requirements of the app, whether date should be blended with other text or not, significancy in the context and other factors. Thankfully, there is an instance method in the Date struct that makes it really easy to present a date as a string, providing quite a few options both for the date and for the time part.
Presenting formatted dates
Let’s start by assigning the current date to a constant:
let date = Date()
The easiest and fastest way to get the date
as a string is by using the formatted()
instance method as seen next:
date.formatted()
The output will be this:
29/8/2024, 11:32 AM
See that the date is presented in a numerical format, while the time is shortened showing only the hour, minutes and time period. No seconds or timezone are present.
Note: The output date string will be automatically localized using the user’s device locale settings.