I'm using SwiftDate framework (see link below) https://github.com/malcommac/SwiftDate
I'd like to print the date and time in current region/local/timeZone. I can achieve this by using the below code without using SwiftDate:
DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .short)
Since, SwiftDate provides a shared date formatter. I'd like to know if the same is possible with SwiftDate.
I tried predrag-samardzic code and it worked. Now that there are two options (to do the same job), one with NSDateFormatter and the other with SwiftDate, I thought of profiling them to see which one is better. Here's the code that I used to profile them:
func testNSDateFormatter() {
for _ in 1...10000 {
print("\(Date().toLocalizedString())")
}
}
func testSwiftDate() {
for _ in 1...10000 {
print("\(Date().localizedDate.toString(.dateTime(.short)))")
}
}
extension Date {
func toLocalizedString(dateStyle: DateFormatter.Style = .short, timeStyle: DateFormatter.Style = .short) -> String {
return DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)
}
var localizedDate: DateInRegion {
return self.in(region: Region(calendar: Calendar.current, zone: Zones.current, locale: Locale.current))
}
}
Here's the screenshot from the profiler.
The result of profiling:
NSDateFormatter - 773x SwiftDate - 2674x
NSDateFormatter is approximately 3.45 times faster than SwiftDate. Based on the above, I'd recommend using NSDateFormatter over SwiftDate.