Skip to content
DeveloperMemos

How to format a Date object into an hours and minutes in Swift using DateFormatter

Swift, DateFormatter1 min read

The first step in formatting a Date object is to create an instance of DateFormatter. DateFormatter is a class that converts between dates and their textual representations. It provides a flexible way to format and parse dates using a variety of built-in formats or customized formats.

Here's an example of creating an instance of DateFormatter:

1let dateFormatter = DateFormatter()

The next step is to set the date format string that we want to use. We can set the date format using the dateFormat property of the DateFormatter instance. For example, if we want to display only the hours and minutes of a date, we can use the "HH:mm" format string. Here's how we can set the date format:

1dateFormatter.dateFormat = "HH:mm"

Once we have set the date format, we can use the string(from:) method of the DateFormatter instance to convert a Date object to a string. Here's an example:

1let date = Date()
2let timeString = dateFormatter.string(from: date)
3print(timeString) // Output: 20:15

In the above example, we first created a Date object using the Date() initializer. We then used the string(from:) method of the DateFormatter instance to convert the Date object to a string using the "HH:mm" format string. Finally, we printed the timeString to the console, which outputs "20:15".

It's important to note that the format string is case-sensitive and must match the format of the date string that we want to parse or generate. Here are some of the commonly used format specifiers for formatting a date:

Format SpecifierDescription
yyyyYear with four digits
yyYear with two digits
MMMMFull name of the month
MMMAbbreviated name of the month
MMMonth with leading zero
MMonth without leading zero
ddDay of the month with leading zero
dDay of the month without leading zero
EEEEFull name of the day of the week
EEEAbbreviated name of the day of the week
HHHour in 24-hour format with leading zero
HHour in 24-hour format without leading zero
hhHour in 12-hour format with leading zero
hHour in 12-hour format without leading zero
mmMinute with leading zero
mMinute without leading zero
ssSecond with leading zero
sSecond without leading zero
aAM/PM marker

In conclusion, formatting a Date object into an hours and minutes string in Swift is simple and straightforward. We can create an instance of DateFormatter, set the date format string, and use the string(from:) method to convert a Date object to a string. By using the appropriate format specifiers, we can customize the date format as per our requirement.