In software development, dealing with dates and times is a common task, whether you’re creating a calendar application, managing timestamps, or formatting dates for user display. But sometimes it becomes confusing when working with multiple countries or Locales. Date and DateFormatter are the main components that are used for Date parsing and text representation.
In this article, we will cover Date, Date format, convert date to string, and string to date with Locale and we will discuss all useful components of DateFormatter in swift
Creating DateFormatter Object–
DateFormatter converts between dates and their textual representations. The Date Formatter in Swift is highly convenient from a developer’s point of view.
let dateFormatter = DateFormatter()
Converting Date to String –
Below is a very simple example of converting Date to String, It is the straightforward function of the DateFormatter class.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = dateFormatter.string(from: Date())
We set the ‘dateFormat’ property to the desired format for what textual representation we need. ‘string(from:)’ is the instance method of the DateFormatter class that converts the Date object to String.
Converting String to Date –
DateFormatter class has another method to convert Date to a String object: Again we take an object of DateFormatter class:
let dateFormatter = DateFormatter()
let dateString = "2023-12-28 15:10:37"
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = dateFormatter.date(from: dateString) {
// Use the formatted date
print(date)
} else {
// Handle error
}
//Output 2023-12-28 09:40:37 +0000
Here, we have dateString as date as text, setting up dateFormate is “my-MM-dd HH:mm:ss”.
Date Format Symbols –
- yyyy: Year (e.g., 2023)
- MM: Month (e.g., 09 for September)
- dd: Day (e.g., 28)
- HH: Hour (e.g., 14 for 2 PM) -it is for 24 format
- hh: Hour for 12 format // in this format we need to add am/pm format
- mm: Minute (e.g., 05)
- ss: Second (e.g., 37)
- z: Time-Zone: specific non-location
dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000
dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600
dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16
dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM
dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000
dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000
dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000
dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM
dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000
Customizable AP/PM symbols–
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
Example –
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
print(dateFormatter.string(from: Date()))
//Outout -06:17 PM
Date Format Styles –
Swift provides us with some default date format styles, We can use them directly with the below properties. DateFormatter allows you to display dates and times according to the user’s preferred locale and formatting conventions:
Date Style –
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
// Output - 28-Dec-2023
Other options are – .short, .full, .long, .none
Note: date and time style format depend on the user’s device’s locale settings (device region or time zone).
Localization with date and time formatting-
If we set the locale property of DateFormatter, In this case, dateFormatter will pick up the local from what you set instead of what is set in the device setting.
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "es")
dateFormatter.dateFormat = "dd MMMM yyyy"
print(dateFormatter.string(from: Date()))
Output // 28 diciembre 2023
If we set locale as
dateFormatter.locale = Locale(identifier: "hi_IN")
//Output -28 दिसंबर 2023
In the above example, we set a locale for Spanish. By setting this locale property, you can make sure that date formatting remains consistent, It will not be changed if device regions are changed.
Best practices for DateFormatter in Swift –
Always create a common function to create Date to String and vice-versa. You can create a common method like the one below where you can pass ‘date format’ as a parameter as per your need.
class CustomDateFormatter {
static func getFormattedStringFromDate(date: Date?, formatter:String) -> String {
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = formatter
return dateFormatterPrint.string(from: date ?? Date())
}
static func getFormattedDateFromString(dateString: String, formatter:String) -> Date? {
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = formatter
return dateFormatterPrint.date(from: dateString)
}
}
Here, the ‘CustomDateFormatter’ class has two functions for ‘date formatter’. it’s a good practice to reuse them whenever possible. Don’t create a new ‘formatted’ object for each date conversion.
Conclusion –
Developers can parse and format dates in accordance with requirements by using the DateFormatter class. Swift provides a very simple way to convert Date to String and vice-versa. A lot of attributes and properties of the Date Formatter class provide a wide variety of in-build date formats.