Converting Dates To Formatted Strings Easily in Swift

No more date formatters and lines of code to convert

Gabriel Theodoropoulos
3 min readSep 12, 2024
Photo by Rene Terp: https://www.pexels.com/photo/calendar-displaying-the-date-2504924/

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.

--

--

Gabriel Theodoropoulos

An iOS & macOS app maker writing code in Swift. Author of countless programming tutorials. Content creator. https://serialcoder.dev