— Swift, DateFormatter — 1 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 Specifier | Description |
---|---|
yyyy | Year with four digits |
yy | Year with two digits |
MMMM | Full name of the month |
MMM | Abbreviated name of the month |
MM | Month with leading zero |
M | Month without leading zero |
dd | Day of the month with leading zero |
d | Day of the month without leading zero |
EEEE | Full name of the day of the week |
EEE | Abbreviated name of the day of the week |
HH | Hour in 24-hour format with leading zero |
H | Hour in 24-hour format without leading zero |
hh | Hour in 12-hour format with leading zero |
h | Hour in 12-hour format without leading zero |
mm | Minute with leading zero |
m | Minute without leading zero |
ss | Second with leading zero |
s | Second without leading zero |
a | AM/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.